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
shanot/imp
tools/maintenance/fix_doxygen_file_lines.py
Python
gpl-3.0
593
0.001686
#!/usr/bin/env python import sys import re """Rewrite the doxygen \\file lines to have the full path to the file.""" def fix(filename): contents = open(filename, "r").read() contents = re.sub( "\\\\file .*\\.h", "\\\\file " + filename[len("build/include/"):], contents, 1) ...
= open(filename, "wr") f.truncate() f.write(contents) if __name__ == '__main__': for f in sys.argv[1:]:
fix(f)
Admicos/DiscordBot
bot/commands/admin/setconf.py
Python
mit
1,156
0.00346
import discord from bot import config from bot import i18n from bot.commands.command import Command class ConfCommand(Command): def requiresAdmin(self): return True def deleteCMDMsg(self): return True def command(self): return "conf" async def do(self, client: discord.Clien...
return await client.send_message(message.channel, i18n.get_localized_str(message
.server.id, "cmd_conf_help"))
sserrot/champion_relationships
venv/Lib/site-packages/networkx/algorithms/link_prediction.py
Python
mit
16,714
0
""" Link prediction algorithms. """ from math import log import networkx as nx from networkx.utils import not_implemented_for __all__ = ['resource_allocation_index', 'jaccard_coefficient', 'adamic_adar_index', 'preferential_attachment', 'cn_soundarajan_hopcroft', ...
u, v, p) where (u, v) is a pair of nodes and p is their preferential attachment score. Examples -------- >>> import networkx as nx >>> G = nx.complete_graph(5) >>> preds = nx.preferential_attachment(G, [(0, 1), (2, 3)]) >>> for u, v, p in preds: ... '(%d, %d) -> %d' % (u, v, p) ...
ial Networks (2004). http://www.cs.cornell.edu/home/kleinber/link-pred.pdf """ def predict(u, v): return G.degree(u) * G.degree(v) return _apply_prediction(G, predict, ebunch) @not_implemented_for('directed') @not_implemented_for('multigraph') def cn_soundarajan_hopcroft(G, ebunch=None,...
adamdoupe/enemy-of-the-state
audit/blind_sqli_time_delay.py
Python
gpl-2.0
6,458
0.017188
''' blind_sqli_time_delay.py Copyright 2008 Andres Riancho This file is part of w3af, w3af.sourceforge.net . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in...
res.append( statement("1 or pg_sleep("+ str(self._wait_time) +")", dbms.POSTGRE) ) res.append( statement("1' or pg_sleep("+ str(self._wait_time) +") or '1'='1", dbms.POSTGRE) ) res.append( statement('1" or pg_sleep('+ str(self._wait_time) +
') or "1"="1', dbms.POSTGRE) ) # TODO: Add Oracle support # TODO: Add XXXXX support return res class statement(object): def __init__(self, sql_command, dbms): self.sql_command = sql_command self.dbms = dbms
walac/linux
Documentation/conf.py
Python
gpl-2.0
20,998
0.007953
# -*- coding: utf-8 -*- # # The Linux Kernel documentation build configuration file, created by # sphinx-quickstart on Fri Feb 12 13:51:46 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated fi...
# unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes...
e, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False primary_domain = 'c' highlight_language = 'none' # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin t...
migasfree/migasfree-launcher
migasfree_indicator/console.py
Python
gpl-3.0
2,190
0.000457
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <alberto@migasfree.org> # Copyright (c) 2015-2016 Jose Antonio Chavarría <jachavar@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publish...
de(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 4
20) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pu...
ioam/holoviews
holoviews/core/data/cudf.py
Python
bsd-3-clause
12,346
0.001863
import sys import warnings try: import itertools.izip as zip except ImportError: pass from itertools import product import numpy as np from .. import util from ..dimension import dimension_name from ..element import Element from ..ndmapping import NdMapping, item_check, sorted_context from .interface import...
))) for d in kdims+vdims: d = dimension_name(d) if len([c for c in columns if c == d]) > 1: raise DataError('Dimensions may not reference duplicated DataFrame ' 'columns (found d
uplicate %r columns). If you want to plot ' 'a column against itself simply declare two dimensions ' 'with the same name. '% d, cls) return data, {'kdims':kdims, 'vdims':vdims}, {} @classmethod def range(cls, dataset, dimension): ...
unioslo/cerebrum
testsuite/tests/test_core/test_utils/test_scriptargs.py
Python
gpl-2.0
925
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unit tests for script argument utilities. """ from __future__ import print_function, unicode_literals import pytest import argparse from Cerebrum.utils.scriptargs import build_callback_action class CallbackCalled(Exception): pass def test_build_callback_action...
with pytest.raises(SystemExit): parser.parse
_args(['this', '--bar'])
tescalada/npyscreen-restructure
tests/testingSliders.py
Python
bsd-2-clause
314
0.015924
import npyscreen import curses def sliderTest(screen): F = npyscreen.Form() F.
add(npyscreen.TitleSlider, name="Slider 1") F.add(npyscreen.TitleSlider, color='STANDOUT', name="Slider 2") F.add(npyscreen.Slider, name="Slider 3") F.edit() if __name__ == "__main__": curses.wrapper(slid
erTest)
GafferHQ/gaffer
python/GafferUI/MenuButton.py
Python
bsd-3-clause
3,944
0.02713
########################################################################## # # Copyright (c) 2012-2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redi...
is software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMP
LIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NO...
gratipay/gratipay.com
gratipay/models/package/team.py
Python
mit
3,131
0.013095
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import uuid from gratipay.models.team import Team as _Team class Team(object): """A :py:class:`~gratipay.models.package.Package` can have a :py:class:`~gratipay.models.team.Team` associated with it. ...
yield '{}-{}'.format(base_name, i) yield uuid.uuid4().hex for slug in slug_options(): if cursor.one('SELECT count(*) FROM teams WHERE slug=%s', (slug,)) == 0: break
team = _Team.insert( slug=slug , slug_lower=slug.lower() , name=slug , homepage='https://www.npmjs.com/package/' + self.name , product_or_service=self.description , owner=owne...
ojii/django-filer
filer/utils/zip.py
Python
mit
916
0.00655
import os #import zipfile # zipfile.open() is only available in Python 2.6, so we use the future version from django.core.files.uploadedfile import SimpleUploadedFile from filer.utils import zipfile def unzip(file): """ Take a path to a zipfile and checks if it is a valid zip file and returns... """ ...
if bad_file: raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
infolist = zip.infolist() print infolist for zipinfo in infolist: print "handling %s" % zipinfo.filename if zipinfo.filename.startswith('__'): # do not process meta files continue thefile = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo)) files.app...
savioabuga/phoenix
phoenix/health/views.py
Python
bsd-3-clause
1,766
0.003964
from django.core.urlresolvers import reverse from smartmin.views import SmartCR
UDL, SmartCreateView, SmartReadView, SmartUpdateView, SmartListView from .models import Treatment from .forms import TreatmentForm class TreatmentCRUDL(SmartCRUDL): model = Treatment actions = ('create', 'read', 'update', 'list') class Create(SmartCreateView): form_class = TreatmentForm f...
fields = ('date', 'description', 'notes', 'animals') def get_animals(self, obj): animals = '' for animal in obj.animals.all(): animals += '<a href=' + reverse('animals.animal_read', args=[animal.id]) + '>' + str(animal) + '</a>, ' return animals[:-2] c...
otsaloma/gaupol
gaupol/agents/format.py
Python
gpl-3.0
2,965
0
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pr...
oject.change_case(rows, doc, "lower") @aeidon.deco.export def _on_use_sentence_case_activate(self, *args): """Change the selected texts to sentence case.""" page = self.get_current_page() rows = page.view.get_selected_rows() col = page.view.get_focus()[1] doc = page.text...
umn_to_document(col) page.project.change_case(rows, doc, "capitalize") @aeidon.deco.export def _on_use_title_case_activate(self, *args): """Change the selected texts to title case.""" page = self.get_current_page() rows = page.view.get_selected_rows() col = page.view.get...
v00d00dem0n/PyCrashCourse
work/ch15/colormap_example.py
Python
gpl-3.0
3,677
0
""" ================== Colormap reference ================== Reference for colormaps included with Matplotlib. This reference example shows all colormaps included with Matplotlib. Note that any colormap listed here can be reversed by appending "_r" (e.g., "pink_r"). These colormaps are divided into the following cate...
lt.subplots(nrows=nrows) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99) axes[0].set_title(cmap_category + ' colormaps', fontsize=14
) for ax, name in zip(axes, cmap_list): ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10) # Turn off *a...
tp81/openmicroscopy
components/tools/OmeroPy/test/integration/gatewaytest/test_connection.py
Python
gpl-2.0
8,597
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright 2009-2013 Glencoe Software, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt pytest fixtures used as defined in conftest.py: - gatewaywrapper - author_testimg """ import omero import Ice from omero.gateway.sc...
he same # session dies. Also in separate processes. # we mimic this by calling setGroupForSessio
n, which calls # sessionservice.getSession, 2 times on cloned connections gatewaywrapper.loginAsAuthor() assert gatewaywrapper.gateway.getSession() is not None c2 = gatewaywrapper.gateway.clone() assert c2.connect(sUuid=gatewaywrapper.gateway._sessionUuid) assert c2.getSe...
davzhang/helix-python-binding
org/apache/helix/store/zk/ZNode.py
Python
apache-2.0
3,019
0.007287
# package org.apache.helix.store.zk #from org.apache.helix.store.zk import * #from java.util import Collections #from java.util import HashSet #from java.util import List #from java.util import Set #from org.apache.zookeeper.data import Stat import copy from kazoo.protocol.states import ZnodeStat from org.apache.helix....
a def setStat(self, stat): """ Returns void Parameters: stat: Stat """ self._stat = stat def getStat(self): """ Returns Stat """ return self._stat def setChildSet(self, childNames): """ Returns void...
List<String> """ # if self._childSet == Collections.emptySet(): if childNames: # if not self._childSet: # self._childSet = set() self._childSet = copy.copy(childNames) # self._childSet.clear() # self._childSet.addAll(childNames) ...
Andrwe/py3status
py3status/modules/scratchpad.py
Python
bsd-3-clause
5,375
0.001674
# -*- coding: utf-8 -*- """ Display number of scratchpad windows and urgency hints. Configuration parameters: cache_timeout: refresh interval for i3-msg or swaymsg (default 5) format: display format for this module (default "\u232b [\?color=scratchpad {scratchpad}]") thresholds: specify color thres...
ad_data(self): tree = self.json_loads(self.parent.py3.command_output(self.tree_command)) leaves = self.find_scratchpad(tree).get("floating_nodes", []) return { "ipc": self.parent.ipc, "scratchpad": len(leaves), "urgent": sum([window["urgent"] for window in lea...
} def find_scratchpad(self, tree): if tree.get("name") == "__i3_scratch": return tree for x in tree.get("nodes", []): result = self.find_scratchpad(x) if result: return result return {} class Py3status: """ """ # available ...
CIGIHub/greyjay
greyjay/articles/migrations/0024_auto_20150722_1928.py
Python
mit
369
0
# -*- codi
ng: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0023_auto_20150716_2129'), ] operations = [ migrations.AlterModelOptions(
name='topic', options={'ordering': ['name']}, ), ]
agilman/django_maps2
maps/signals.py
Python
mit
601
0.018303
#print("OK, imported signal handling") from registration.signals import user_registered import os from django_maps2 import settings #This callback is listening for user to register. Creates directories for user images. def postRegistration(sender,user,request, **kwargs): m
edia_root = settings.USER_MEDIA_ROOT if not os.path.exists(media_root +"/"+ str(user.pk)): os.mkdir(media_root + "/" + str(user.pk)) os.mkdir(media_root + "/" + str(user.pk)+"/profile_pictures") #print("hello, got user registration signal") user_registered.connect(postRegist
ration)
rwgdrummer/maskgen
plugins/OutputPDF/__init__.py
Python
bsd-3-clause
1,012
0.021739
from PIL import Image from maskgen import exif import numpy as np import PIL """ Save the image as PDF. If the image has a orientation and 'Image Rotated', rotate the image according to the EXIF. """ def transform(img,source,target, **kwargs): if 'resolution' in kwargs: res = float(int(kwargs['resolution']...
'version':PIL.__version__, 'arguments':{ 'resolution':{
'type':'int', 'defaultvalue':'100', 'description':'DPI' } }, 'transitions': [ 'image.image' ] } def suffix(): return '.pdf'
egnyte/gitlabform
tests/acceptance/test_branches.py
Python
mit
32,440
0.001326
import pytest from gitlabform.gitlab import AccessLevel from tests.acceptance import ( run_gitlabform, DEFAULT_README, get_gitlab, ) gl = get_gitlab() @pytest.fixture(scope="function") def branches(request, gitlab, group_and_project): branches = [ "protect_branch_but_allow_all", "pr...
d_to_merge", "protect_branch_and_allow_access_l
evels_with_user_ids", "protect_branch", ] for branch in branches: gitlab.create_branch(group_and_project, branch, "main") def fin(): for branch in branches: gitlab.delete_branch(group_and_project, branch) gitlab.set_file( group_and_project, ...
venmo/slouch
example.py
Python
mit
2,870
0.001742
#!/usr/bin/env python """ TimerBot can manage multiple stopwatch-style timers from Slack. Usage: timerbot [--start_fmt=<start_fmt>] [--stop_fmt=<stop_fmt>] <slack_token> timerbot --help Options: --start_fmt=<start_fmt> Format string for start responses (given a datetime) [default: {}] --stop_fmt=<stop_fmt>...
w return bot.start_fmt.format(now) @TimerBot.command def stop(opts, bot, event): ""
"Usage: stop [--name=<name>] [--notify=<slack_username>] Stop a timer. _name_ works the same as for `start`. If given _slack_username_, reply with an at-mention to the given user. """ name = opts['--name'] slack_username = opts['--notify'] now = datetime.datetime.now() delta = now - ...
anhstudios/swganh
data/scripts/templates/object/static/structure/general/shared_fountain_generic_style_1.py
Python
mit
462
0.047619
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swg
py.object import * def create(kerne
l): result = Static() result.template = "object/static/structure/general/shared_fountain_generic_style_1.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
toladata/TolaActivity
factories/django_models.py
Python
apache-2.0
848
0
from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from workflow.models import ROLE_PROGRAM_ADMIN class User(DjangoModelFactory): class Meta: model = 'auth.User'
django_get_or_create = ('username',)
first_name = 'Thom' last_name = 'Yorke' username = lazy_attribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = lazy_attribute(lambda o: o.username + "@testenv.com") class Group(DjangoModelFactory): class Meta: model = 'auth.Gr...
eike-welk/clair
src/clairweb/clairweb/wsgi.py
Python
gpl-3.0
394
0
""" WSGI config for
clairweb 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.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "clai...
= get_wsgi_application()
alanmcna/timelapsecontroller
focusandshoot.py
Python
gpl-2.0
2,409
0.034454
import sqlite3 import RPi.GPIO as GPIO import os, sys, time conn = sqlite3.connect( os.path.join( os.path.dirname(os.path.realpath(sys.argv[0])), 'db/timelapsecontroller.db')) conn.row_factory = sqlite3.Row sleep=2 def set_pid(pid=None): c = conn.cursor() try: # Update the DB counter c.execute("UPDATE ...
oard Mode GPIO.setmode(GPIO.BOARD) #Write (set) PID to config set_pid(os.getpid()) while True: if ( running() ): wakeup() shoot() updatecounter() #Pause for configured # of seconds (default 2) sleep = getsleep() print "Sleeping for %r seconds.." % sleep time.sleep(sleep)...
id(None) # close the DB conn conn.close() #Stops the script and End of script clean up of the GPIO Port GPIO.cleanup()
dalou/django-extended
django_extended/fields/price.py
Python
bsd-3-clause
873
0.003436
# -*- coding: utf-8 -*- from django.db import models
from django import forms from django.utils.text import capfirst fr
om ..forms import PriceField as PriceFormField, PriceInput class PriceField(models.DecimalField): """ A text field made to accept hexadecimal color value (#FFFFFF) with a color picker widget. """ def __init__(self, *args, **kwargs): kwargs['decimal_places'] = kwargs.get('decimal_places', 2...
miteshvp/fabric8-analytics-worker
f8a_worker/schemas.py
Python
gpl-3.0
15,518
0.00116
"""U
tilities for accessing and working with JSON schemas.""" import abc from collections import namedtuple, OrderedDict from functools import wraps import importlib import json import os.path import pkgutil import jsl import jsonschema def added_in(role): """Pr
ovide helper for schema fields added in a particular version. Example: with added_in(ROLE_v2_0_0) as since_v2_0: since_v2_0.new_field_name = ... """ return jsl.Scope(lambda v: v >= role) def removed_in(role): """Provide helper for schema fields removed in a particular version. ...
mozilla-lockbox/lockbox-extension
test/integration/pages/util/__init__.py
Python
mpl-2.0
43
0
"""Con
tain utility functions and tools."""
fedjo/thesis
project/aat/forms.py
Python
apache-2.0
3,217
0.009636
from django import forms from aat.models import RecognizerPreTrainedData class DefaultDetectionForm(forms.Form): title = "Please specify the directory containing your videos" #video = forms.FileField(required=True, widget=forms.ClearableFileInput()) video = forms.CharField(widget=forms.TextInput(attrs={'c...
Field(widget=forms.HiddenInput(), required=True, initial=False) transcription = forms.CharField(widget=forms.HiddenInput(), required=True, initial=False)
#iszip = forms.ChoiceField(choices=CHOICES, # widget=forms.RadioSelect(attrs={'data-toggle': 'radio'})) scale = forms.FloatField(widget=forms.NumberInput(attrs={'class': 'form-control', 'step': '0.1', 'placeholder': '1.3'})) neighbors = forms.IntegerField(widget=forms.NumberInput...
ddurieux/alignak
alignak/objects/servicegroup.py
Python
agpl-3.0
7,989
0.000751
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors # # This file is part of Alignak. # # Alignak 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 Free So...
wing copyright and # permission notice: # # Copyright (C) 2009-2014: # Hartmut Goebel, h.goebel@goebel-consult.de # Guillaume Bour, guillaume@bour.cc # Nicolas Dupeux, nicolas@dupeux.net # Grégory Starck, g.starck@gmail.com
# Gerhard Lausser, gerhard.lausser@consol.de # Sebastien Coavoux, s.coavoux@free.fr # Christophe Simon, geektophe@gmail.com # Jean Gabes, naparuba@gmail.com # Romain Forlot, rforlot@yahoo.com # This file is part of Shinken. # # Shinken is free software: you can redistribute it and/or modify # it...
jfisteus/ztreamy
ztreamy/tools/utils.py
Python
gpl-3.0
9,124
0.001534
# ztreamy: a framework for publishing semantic events on the Web # Copyright (C) 2011-2015 Jesus Arias Fisteus # # 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, ...
me_scale) else: fire_time = self._time_generator.next() self.io_loop.add_timeout(fire_t
ime, pub.publish) return fire_time def _check_if_finished(self): self._pending_events = [p for p in self._pending_events \ if not p.finished] if len(self._pending_events) == 0: self._send_closing_event() def _send_closing_event(self): # ...
aitoralmeida/geo-lak
LAK_2014/LAK_2014/urls.py
Python
gpl-2.0
657
0.001522
# coding: utf-8 from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'LAK_2014.views
.index', name='index'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.adm
indocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), ) urlpatterns += staticfiles_urlpatterns() handler404 = 'LAK_2014.views.view404'
cloudify-cosmo/cloudify-dsl-parser
dsl_parser/interfaces/operation_merger.py
Python
apache-2.0
8,610
0
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. 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...
ode_type_operation == NO_OP: return NO_OP merged_operation_implementation = \ self.overriding_node_type_operation['implementation'] merged_operation_inputs = \ self.overriding_node_type_operation['inputs'] merged_operation_exe
cutor = \ self.overriding_node_type_operation['executor'] merged_operation_max_retries = \ self.overriding_node_type_operation['max_retries'] merged_operation_retry_interval = \ self.overriding_node_type_operation['retry_interval'] return operation_mapping(...
cnobile2012/inventory
inventory/categories/api/tests/test_categories_api.py
Python
mit
33,305
0.000961
# -*- coding: utf-8 -*- # # inventory/categories/api/tests/test_categories_api.py # from django.contrib.auth import get_user_model from rest_framework.reverse import reverse from rest_framework import status from rest_framework.test import APITestCase from inventory.categories.models import Category from inventory.c...
['name'] = 'TestCategory-05' pdu = data.setdefault('PDU', su.copy()) pdu['name'] = 'TestCategory-06' self._test_project_users_with_valid_permissions( uri, method, project_user=False, request_data=data) def test_OPTIONS_category_list_with_invalid_permissions(self): """ ...
s' uri = reverse('category-list') self._test_users_with_invalid_permissions(uri, method) self._test_project_users_with_invalid_permissions(uri, method) def test_OPTIONS_category_list_with_valid_permissions(self): """ Test that the method OPTIONS brings back the correct data....
plotly/plotly.py
packages/python/plotly/plotly/graph_objs/scattersmith/marker/colorbar/_title.py
Python
mit
7,130
0.001543
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Title(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "scattersmith.marker.colorbar" _path_str = "scattersmith.marker.colorbar.title" _valid_props =...
@property def text(self): """ Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specifie...
number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val # Self properties description # --------------------------- @property def _prop_descriptions(self): ...
RamonGuiuGou/l10n-spain
l10n_es_aeat/models/l10n_es_aeat_map_tax_line.py
Python
agpl-3.0
1,386
0
# -*- coding: utf-8 -*- # Copyright 2013-2016 Pedro M. Baeza <pedro.baeza@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl from openerp import fields, models class L10nEsAeatMapTaxLine(models.Model): _name = 'l10n.es.aeat.map.tax.line' _order = "field_number asc, id asc" fiel...
('base', 'Base'), ('amount', 'Amount'), ], string="Field type", default='amount') sum_type = fields.Selection( selection=[ ('credit', 'Credit'),
('debit', 'Debit'), ('both', 'Both (Credit - Debit)'), ], string="Summarize type", default='both') inverse = fields.Boolean(string="Inverse summarize sign", default=False) to_regularize = fields.Boolean(string="To regularize")
schaabs/sandbox
net/sandbox.keyvault/python/repl/secrets.py
Python
mit
160
0
from key_vault_agent
import KeyVaultAgent class SecretsAgent(KeyVaultAgent): def get_secret(self): self.data_client.restore_
secret() pass
proyectosdeley/proyectos_de_ley
proyectos_de_ley/pdl/migrations/0002_proyecto_legislatura.py
Python
mit
492
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-09-02 20:
49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pdl', '0001_initial'
), ] operations = [ migrations.AddField( model_name='proyecto', name='legislatura', field=models.IntegerField(default=2011, max_length=4), preserve_default=False, ), ]
ctk3b/InterMol
intermol/forces/cubic_bond_type.py
Python
mit
1,664
0.006611
import simtk.unit as units from intermol.decorators import accepts_compatible_units from intermol.forces.abstract_bond_type import AbstractBondType class CubicBondType(AbstractBondType): __slots__ = ['length', 'C2', 'C3', 'order', 'c'] @accepts_compatible_units(None, None, len...
""" stub documentation """ def __init__(self, atom1, atom2, bondingtype1=None, bondingtype2=None, length=0.0 * units.nanometers, C2=0.0 * units.kilojoules_per_mole * units.nanometers ** (-2), C3=0.0 * units.kilojoules_per_mole * units.nanometers ** (-3)...
length=length, C2=C2, C3=C3, order=order, c=c)
tpn/msmtp
scripts/msmtp-gnome-tool/msmtp-gnome-tool.py
Python
gpl-3.0
6,270
0.005423
#!/usr/bin/python # -*- coding: utf-8 -*- """ Set/get passwords for MSMTP or MPOP in Gnome Keyring Copyright (C) 2009 Gaizka Villate 2010 Emmanuel Bouthenot Original author: Gaizka Villate <gaizkav@gmail.com> Other author(s): Emmanuel Bouthenot <kolter@openics.org> URL: http://github.com/gaizka/misc-s...
in server '%s'" % (username, server) ret = False if ret:
gk.item_delete_sync(self.keyring, results[0]['item_id']) print "Password successfully removed" return ret def main(): ret = True km = keyringManager() parser = optparse.OptionParser(usage="%prog [-s|-g|-d] --username myuser --server myserver") parser.add_option("-s", "--s...
transcript/samsa_v2
python_scripts/DIAMOND_results_filter.py
Python
gpl-3.0
5,358
0.01885
#!/usr/lib/python2.7 ########################################################################## # # Copyright (C) 2015-2016 Sam Westreich # # 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; # # T...
xt_elem + " " + second_elem if "-O" in sys.argv: target_org_outfile = open(string_find("-O"), "w") else: target_org_outfile = open(infile_name[:-4] + "_" + target_org + ".tsv", "w") else: sys.exit("Need to specify target organism or function to filter by, using -SO flag.") # loading database file if "-D" in sy...
db = open(string_find("-D"), "r") else: sys.exit("WARNING: database must be specified using '-D' flag.") # Getting the database assembled db_org_dictionary = {} db_id_dictionary = {} db_line_counter = 0 db_error_counter = 0 t0 = time.time() for line in db: if line.startswith(">") == True: db_line_counter += 1 ...
rchurch4/georgetown-data-science-fall-2015
data_preparation/data_preparation_trip_advisor.py
Python
mit
4,646
0.007964
# Ravi Makhija # data_preparation_trip_advisor.py # Version 4.2 # # Description: # This script takes as input the json files generated # from scraping TRIP ADVISOR, and initiates the following # data preparation sequence: # 1) Converts json to csv, making each row of the # csv a unique review with restaurant in...
generating file paths above ################ # We proceed with a user prompt, then the data preparation sequence ######
########## # Warn user about possibly overwriting csvs. # Uses a loop to ensure valid input. # Also, prompt the user to enter in the city that corresponds to # the restaurants in the input data. Since restaurant location is # not a field in the input data, this has to be set at run time, # and this also means all the ...
datalogics/scons
test/ParseDepends.py
Python
mit
5,431
0.002578
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, ...
TestSCons.TestSCons() test.subdir('subdir', 'sub2') test.write(
'build.py', r""" import sys contents = open(sys.argv[2], 'rb').read() + open(sys.argv[3], 'rb').read() file = open(sys.argv[1], 'wb') file.write(contents) file.close() """) test.write('SConstruct', """ Foo = Builder(action = r'%(_python_)s build.py $TARGET $SOURCES subdir/foo.dep') Bar = Builder(action = r'%(_python_)...
mperignon/component_creator
topoflow_creator/topoflow/channels_base.py
Python
gpl-2.0
124,876
0.012324
## See "d_bankfull" in update_flow_depth() ######## (2/21/13) ## See "(5/13/10)" for a temporary fix. #------------------------------------------------------------------------ # Copyright (c) 2001-2014, Scott D. Peckham # # Sep 2014. Wrote new update_diversions(). # New standard names and BMI updates ...
th-slope product) # update_shear_speed() # (9/9/14) # update_trapezoid_Rh() # update_friction_factor() # (9/9/14) #---------------------------------- # update_velocity() # (override as needed) # update_velocity_on_edges() # update_froude_number() # (9/9/14) #--...
peak_values() # (at the main outlet) # update_Q_out_integral() # (moved here from basins.py) # update_mins_and_maxes() # (don't add into update()) # check_flow_depth() # check_flow_velocity() #---------------------------------- # open_input_files() # read_input_files() # ...
yuhangc/planning_algorithms
environment/robots/humans.py
Python
mit
1,684
0
from environment.robots.robot2d_base import Robot2dCircular from environment.robots.robot_utils import * class HumanSimple(Robot2dCircular): def __init__(self, size=0.3, max_vel=2.0, max_acc=5.0, uncertainty=0.0): super(HumanSimple, self).__init__(size) self.max_v = max_vel self.max_acc =...
def update(self, u, dt): """ Dynamic update, input is the "social force" that drives people :param u: (fx, fy) :param dt: time step """ # calculate the force that drives people to goal x_rel_goal = self.x_goal - np.array([self.x, self.y]) v_goal
= self.vd * x_rel_goal / np.linalg.norm(x_rel_goal) f_goal_x = self.k * (v_goal[0] - self.vx) f_goal_y = self.k * (v_goal[1] - self.vy) # calculate accelerations ax = f_goal_x + u[0] - self.c * self.vx ay = f_goal_y + u[1] - self.c * self.vy # update velocity and posi...
sch3m4/intelmq
intelmq/tests/bots/parsers/dragonresearchgroup/test_parser_ssh.py
Python
agpl-3.0
598
0.001672
# -*- coding: utf-8 -*- from __future__ import unicode_litera
ls import json import unittest import intelmq.lib.test as test from intelmq.bots.parsers.dragonresearchgroup.parser_ssh import \ DragonResearchGroupSSHParserBot class TestDragonResearchGroupSSHParserBot(test.BotTestCase, unittest.TestCase): """ A TestCase for DragonResearchGroupSSHParserBot. """ ...
_ == '__main__': unittest.main()
individual-it/office-traffic-light
manage.py
Python
gpl-3.0
804
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "office.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import
may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError(
"Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
Fogapod/VKBot
bot/plugins/plugin_stop.py
Python
mit
684
0.001894
# co
ding:utf8 class Plugin(object): __doc__ = '''Плагин предназначен для остановки бота. Для использования необходимо иметь уровень доступа {protection} или выше Ключевые слова: [{keywords}] Использование: {keyword} Пример: {keyword}''' name = 'stop' keywords = (u'стоп', name, '!') protec...
return rsp
dnaextrim/django_adminlte_x
adminlte/static/plugins/datatables/extensions/ColReorder/examples/simple.html.py
Python
mit
17,013
0.036972
XXXXXXXXX XXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXX X XXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXX...
XXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXX XXXX X
XXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXX XXXX XXXXXXXXXX XXXXXXXX XXXXXXXXXX XXXXXXXXX XXXXXXXXXXX XXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX...
vishnu2kmohan/dcos-commons
frameworks/template/tests/test_overlay.py
Python
apache-2.0
945
0.003175
import os import pytest import sdk_install import sdk_networks import sdk_utils from tests import config overlay_nostrict = pytest.mark.skipif(os.environ.get("SECURITY") == "strict", reason="overlay tests currently broken in strict") @pytest.fixture(scope='module', autouse=True) def configure_package(configure_s...
tall.uninstall(config.PACKAGE_NAME, config.SERVICE_NAME) sdk_install.install( config.PACKAGE_NAME, config
.SERVICE_NAME, config.DEFAULT_TASK_COUNT, additional_options=sdk_networks.ENABLE_VIRTUAL_NETWORKS_OPTIONS) yield # let the test session execute finally: sdk_install.uninstall(config.PACKAGE_NAME, config.SERVICE_NAME) @pytest.mark.sanity @pytest.mark.smoke @pytest.mark.over...
coreyoconnor/nixops
tests/functional/test_deploys_nixos.py
Python
lgpl-3.0
238
0.004202
from nose import tools from tests.functional import single_ma
chine_test class TestDeploysNixos(single_machine_test.SingleMachineTest): def run_check(self): self.depl.deploy() self.check_command("test -f /etc/NIXO
S")
Moshifan100/pythongame
game.py
Python
gpl-3.0
15,122
0.002711
#!/usr/bin/python3 from itertools import cycle import random import sys import math import os import pygame import pickle from pygame.locals import * pgimagel = pygame.image.load FPS = 30 SCREENWIDTH = 288 SCREENHEIGHT = 512 # amount by which base can maximum shift to left PIPEGAPSIZE = 100 # gap between upper and l...
lowPipes = [ {'x': SCREENWIDTH + 200, 'y': newPipe1[1]['y']}, {'x': SCREENWIDTH + 200 + (SCREENWIDTH / 2), 'y': newPipe2[1]['y']}, ] pipeVelX = -4 # player velocity, max velocity, downward ac
cleration, accleration on flap playerVelY = -9 # player's velocity along Y, default same as playerFlapped playerMaxVelY = 10 # max vel along Y, max descend speed playerMinVelY = -8 # min vel along Y, max ascend speed playerAccY = 1 # players downward accleration playerFlapAcc = -...
burk/helgapp
manage.py
Python
mit
250
0
#!/usr/bin/env python import os import s
ys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "helgapp.settings") from django.core.management impo
rt execute_from_command_line execute_from_command_line(sys.argv)
Donkyhotay/MoonPy
zope/security/tests/test_adapter.py
Python
gpl-3.0
948
0
############################################################################## # # Copy
right (c) 2004 Zope Corporation and Contributors. # All R
ights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTI...
bkidwell/caliload
caliload/metadata.py
Python
gpl-3.0
3,883
0.023178
# Copyright 2011 Brendan Kidwell <brendan@glump.net>. # # This file is part of caliload. # # caliload 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 ...
opf .""" from caliload.configobject import ConfigObject from caliload.optionsobject import OptionsObject from glob import glob from uuid import uuid1 from xml.dom import minidom import os import subprocess config = ConfigObject() options = OptionsObject() import logging log = logging.getLogger(__name__) def get_tex...
ODE: rc.append(node.data) return ''.join(rc) def get_book_filename(dir): file = None for ext in ("epub", "pdf"): if not file is None: break for n in glob(os.path.join(dir, "*.%s" % ext)): if not n[0] == '_': file = n filetype = ext break if file is None: raise RuntimeError("Can't find an eb...
chromium/chromium
third_party/android_deps/libs/com_android_support_support_media_compat/3pp/fetch.py
Python
bsd-3-clause
2,505
0
#!/usr/bin/env python3 # Copyright 2021 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. # This is generated, do not edit. Update BuildConfigGenerator.groovy and # 3ppFetch.template instead. import argparse import json imp...
is commonly the case). latest = re.findall('<version>([^<]+)</version>', metadata)[-1] print(latest + f'.{_PATCH_VERSION}') def get_download_url(version): # Remove the patch version when getting the download url version_no
_patch, patch = version.rsplit('.', 1) if patch.startswith('cr'): version = version_no_patch file_url = '{0}/{1}/{2}/{3}/{2}-{3}.{4}'.format(_REPO_URL, _GROUP_NAME, _MODULE_NAME, version, _FILE_EXT) ...
dolphinkiss/cookiecutter-django-aws-eb
{{cookiecutter.project_name}}/wsgi_extra.py
Python
mit
145
0
# wraps djangos normal wsgi application in whitenose from whitenoise.djan
go imp
ort DjangoWhiteNoise application = DjangoWhiteNoise(application)
TacticalGoat/reddit
DelayBot/delaybot.py
Python
mit
3,987
0.021319
#This bot was written by /u/GoldenSights for /u/FourMakesTwoUNLESS on behalf of /r/pkmntcgtrades. Uploaded to GitHub with permission. import praw import time import datetime import sqlite3 '''USER CONFIGURATION''' APP_ID = "" APP_SECRET = "" APP_URI = "" APP_REFRESH = "" # https://www.reddit.com/comments/3cm1p8/how_t...
ame=?', [pautho
r]) cur.execute('INSERT INTO users VALUES(?, ?)', (pauthor, pid)) sql.commit() print('\t' + pauthor + "'s database info has been reset.") else: differences = '%.0f' % (DELAY - difference) timestring = str(datetime.timedelta(seconds=float(differences))) timestring = timestring.re...
mhruscak/pyparted
tests/test_parted_filesystem.py
Python
gpl-2.0
2,438
0.002461
# # Test cases for the methods in the parted.filesystem module itself # # Copyright (C) 2009-2011 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) a...
POSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Bost
on, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # # Red Hat Author(s): David Cantrell <dcantrell@redhat.com> # import unitt...
Tsumiki-Chan/Neko-Chan
classes/messagehandler.py
Python
gpl-3.0
1,344
0.005952
from functions import logger, config import asyncio class MessageHandler: def __init__(self, client, message, command, args): ''' Create a new messagehandler which handles the required parts for the commands. disabling this module will fuck up the whole bot.''' self.client = client ...
text, channel=None): ''' Sends a te
xt message to a channel. Arguments: (str) text: The message you want to send (Optional) channel: The channel you want the message to be sent in Returns: An messageobject if the message has been sent, None otherwise.''' message = None text = str(text) ...
rossjones/ScraperWikiX
web/urls.py
Python
agpl-3.0
3,556
0.005062
from django.conf.urls.defaults import * import frontend.views as frontend_views import codewiki.views import codewiki.viewsuml from django.contrib.syndication.views import feed as feed_view from django.views.generic import date_based, list_detail from django.views.generic.simple import direct_to_template f...
to be the easiest way unfortunately. from django.contrib.auth.models import User User._meta.ordering = ['username'] from frontend.feeds import LatestCodeObjects, LatestCodeObjectsBySearchTerm, LatestCodeObjectsByTag, LatestViewObjects, LatestScraperObjects feeds = { 'all_code_objects': LatestCodeObjects...
ViewObjects, 'latest_code_objects_by_search_term': LatestCodeObjectsBySearchTerm, 'latest_code_objects_by_tag': LatestCodeObjectsByTag, } urlpatterns = patterns('', url(r'^$', frontend_views.frontpage, name="frontpage"), # redirects from old version (would clashes if you happen to have a scr...
jorgecarleitao/public-contracts
main/__init__.py
Python
bsd-3-clause
140
0
# See e.g. http://stackoverflow.com/
a/14076841/931303 try: import pymysql pymysql.install_as_M
ySQLdb() except ImportError: pass
nmercier/linux-cross-gcc
win32/bin/Lib/distutils/command/install_scripts.py
Python
bsd-3-clause
2,132
0.003752
"""distutils.command.install_scripts Implements the Distutils 'install_scripts' command, for installing Py
thon scripts.""" # contributed by Bastian Kleineidam __revision__ = "$Id$" import os from distutils.core import Command from distutils import log from stat import ST_MODE class install_scripts (Command):
description = "install scripts (Python or otherwise)" user_options = [ ('install-dir=', 'd', "directory to install scripts to"), ('build-dir=','b', "build directory (where to install from)"), ('force', 'f', "force installation (overwrite existing files)"), ('skip-build', None...
BlogomaticProject/Blogomatic
opt/blog-o-matic/usr/lib/python/Bio/Encodings/IUPACEncoding.py
Python
gpl-2.0
5,460
0.000733
"""Properties once used for transcription and translation (DEPRECATED). This module is deprecated, and is expected to be removed in the next release. If you use this module, please contact the Biopython developers via the mailing lists. """ #NOTE - Adding a deprecation warning would affect Bio.Alphabet.IUPAC # Set up...
le.nucleotide_alphabet.__class__]["translator"] = obj set_prop[obj.table.protein_alphabet.__class__]["ambiguous_translator"] = obj for id, obj in Translate.ambiguous_rna_by_id.iteritems(): property = "translator.id.%d" % id set_prop[obj.table.nucleotide_alphabet.__class__][property] = obj property...
d == 1: set_prop[obj.table.nucleotide_alphabet.__class__]["translator"] = obj set_prop[obj.table.protein_alphabet.__class__]["ambiguous_rna_translator"] = obj
learntextvis/textkit
textkit/filter/filter_lengths.py
Python
mit
491
0
import click from textkit.utils import output, read_tokens
@click.command() @click.argument('tokens', type=click.File('r'), default=click.open_file('-')) @click.option('-m', '--minimum', default=3, help='Minimum length of token to not filter.', show_default=True) def filterlengths(minimum, tokens): '''Remove tokens that are shorter th
en the minimum length provided.''' content = read_tokens(tokens) [output(token) for token in content if len(token) >= minimum]
Tim---/osmo-tetra
src/demod/python/cqpsk.py
Python
agpl-3.0
14,762
0.009619
# # Copyright 2005,2006,2007 Free Software Foundation, Inc. # # cqpsk.py (C) Copyright 2009, KA1RBI # # This file is part of GNU Radio # # GNU Radio 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 ver...
ges try: from gnuradio import modulation_utils except ImportError: from gnuradio import digital _def_has_gr_dig
ital = True # default values (used in __init__ and add_options) _def_samples_per_symbol = 10 _def_excess_bw = 0.35 _def_gray_code = True _def_verbose = False _def_log = False _def_costas_alpha = 0.15 _def_gain_mu = None _def_mu = 0.5 _def_omega_relative_limit = 0.005 # //////////////////////////////////////////////...
mhkyg/OrangePIStuff
motion/motion.py
Python
mit
2,565
0.061009
#!/usr/bin/python # coding=UTF-8 #import RPi.GPIO as GPIO_detector #raspberry version from pyA20.gpio import gpio import time import datetime import locale import sys import os from char_lcd2 import OrangePiZero_CharLCD as LCD def file_get_contents(filename): with open(filename) as f: return f.read() ...
ijelzo.txt"); for x in range(0, 4): if (x % 2) == 0 : time_data = datetime.datetime.now().strftime('%Y-%m-%d') +' '+ datetime.datetime.now().strftime('%H:%M:%S') +'\n'+ week_days[int(datetime.datetime.now().strftime('%w'))] ; lcd.clear() lcd.message(time_data); else: lcd.clear()...
print(lcd_text); lcd.clear() lcd.set_backlight(1) gpio.setcfg(PIR_PIN, gpio.INPUT) gpio.pullup(PIR_PIN, gpio.PULLUP) # endless loop try: #GPIO_detector.add_event_detect(PIR_PIN, GPIO_detector.RISING, callback=MOTION, bouncetime=300) print("event atached start loop"); count = 0 while...
Agrajag-Petunia/existential-romantic-novel
run.py
Python
mit
1,939
0
from datetime import datetime from src.textgenerator import TextGenerator from src.utils import extract_project_gutenberg_novel, remove_titles # The source files to use # NOTE: Ulysses makes the generated text just a little too weird. files = [ './data/life_and_amours.txt', './data/memoirs_of_fanny_hill.txt',...
remove project gutenberg license stuff from the text text = extract_project_gutenberg_novel(fobj.read()) # Strip the title, chapters, etc from the text. text = remove_titles(text) # Learn the cleaned up text model.learn(text) # Start generating our novel with open('./data/nove...
ou are free and that is why you lust\n") fobj.write("=====================================\n\n") fobj.write("Author: Agrajag Petunia's computer\n") fobj.write("Generation Date: {}\n\n".format( datetime.now().strftime("%Y-%m-%d") )) # For each chapter generate some text for c in range(1,...
pyfa-org/Pyfa
gui/auxWindow.py
Python
gpl-3.0
2,871
0.001393
# ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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 ...
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 pyfa. If not, see <http://www.gnu.org/licenses/>. # ===============================================================
============== # noinspection PyPackageRequirements import wx class AuxiliaryMixin: _instance = None def __init__(self, parent, id=None, title=None, pos=None, size=None, style=None, name=None, resizeable=False): baseStyle = wx.FRAME_NO_TASKBAR | wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU i...
nandhp/youtube-dl
youtube_dl/extractor/porn91.py
Python
unlicense
2,707
0.00076
# encoding: utf-8 from __future__ import unicode_literals from ..compat import ( compat_urllib_parse_unquote, compat_urllib_parse_urlencode, ) from .common import InfoExtractor from ..utils import ( parse_duration, int_or_none, ExtractorError, ) class Porn91IE(InfoExtractor): IE_NAME = '91por...
, 'max_vid': max_vid,
}) info_cn = self._download_webpage( 'http://91porn.com/getfile.php?' + url_params, video_id, 'Downloading real video url') video_url = compat_urllib_parse_unquote(self._search_regex( r'file=([^&]+)&', info_cn, 'url')) duration = parse_duration(self._search_...
trichter/sito
bin/noise/noise_s_final_autocorr2.py
Python
mit
5,012
0.006185
#!/usr/bin/env python # by TR from obspy.core import UTCDateTime as UTC from sito.data import IPOC from sito.noisexcorr import (prepare, get_correlations, plotXcorrs, noisexcorrf, stack) from sito import util import matplotlib.pyplot as plt from sito.stream import read from multiprocessing ...
elation[1][:-1] # dist = data.stations.dist(*stations) ## if dist >= 120: ## t = (dist // 100) * 50 + 50 ## else: ## t = 70 # t = 200 # stream = data.readDayXcorr(correlation, t1, t2) # if len(stream) > 0: # stream.plotXcorr(-t, t, imshow=True, ...
copilla event', # dateformatter='%y-%m-%d', show=False, # save=data.getPlotX(correlation, 'Tocopilla_0.01.png'), # stack_lim=None) # # method = 'rm5_filter0.1-1' # data = IPOC(xcorr_append='/tests/' + method, use_loca...
teonlamont/mne-python
mne/viz/evoked.py
Python
bsd-3-clause
94,662
0.000011
# -*- coding: utf-8 -*- """Functions to plot evoked M/EEG data (besides topographies).""" from __future__ import print_function # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # ...
s(times - xmax).argmin() fig, axarr = plt.subplots(1, len(ch_types), squeeze=False, figsize=(3 * len(ch_types), 3)) for idx, ch_type in enumerate(ch_types): if ch_type not in ('eeg', 'grad', 'mag'): continu
e picks, pos, merge_grads, _, ch_type = _prepare_topo_plot( info, ch_type, layout=None) if len(pos) < 2: fig.delaxes(axarr[0][idx]) continue this_data = data[picks, minidx:maxidx] if merge_grads: from ..channels.layout import _merge_grad_da...
tiborsimko/invenio-formatter
invenio_formatter/config.py
Python
mit
479
0
# -*- coding: utf-8 -*- # #
This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Configuration for Invenio-Formatter.""" from __future__ import absolute_import, print_
function FORMATTER_BADGES_ALLOWED_TITLES = ['DOI'] """List of allowed titles in badges.""" FORMATTER_BADGES_TITLE_MAPPING = {} """Mapping of titles."""
endolith/numpy
setup.py
Python
bsd-3-clause
17,447
0.002923
#!/usr/bin/env python3 """ NumPy is the fundamental package for array computing with Python. It provides: - a powerful N-dimensional array object - sophisticated (broadcasting) functions - tools for integrating C/C++ and Fortran code - useful linear algebra, Fourier transform, and random number capabilities - and muc...
class new_build_clib(build_clib): def build_a_library(self, build_info, lib_name
, libraries): if _is_using_gcc(self): args = build_info.get('extra_compiler_args') or [] args.append('-std=c99') build_info['extra_compiler_args'] = args build_clib.build_a_library(self, build_info, lib_name, libraries) class new_build_ext(bui...
yotchang4s/cafebabepy
src/main/python/test/test_fileinput.py
Python
bsd-3-clause
38,669
0.001215
''' Tests for fileinput module. Nick Mathewson ''' import os import sys import re import fileinput import collections import builtins import unittest try: import bz2 except ImportError: bz2 = None try: import gzip except ImportError: gzip = None from io import BytesIO, StringIO from fileinput import F...
finally: sys.stdout = savestdout fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) for line in fi: self.assertEqual(line[-1], '\n') m = pat.match(line[:-1]) self.assertNotEqual(m, None) self.assertEqual(int(m.group(1)), fi.filelineno()) ...
*args, **kwargs): self.invoked = True raise self.exception_type() class FileInputTests(unittest.TestCase): def test_zero_byte_files(self): t1 = t2 = t3 = t4 = None try: t1 = writeTmp(1, [""]) t2 = writeTmp(2, [""]) t3 = writeTmp(3, ["The only li...
dmsurti/mayavi
examples/mayavi/mlab/spherical_harmonics.py
Python
bsd-3-clause
1,373
0
""" Plot spherical harmonics on the surface of the sphere, as well as a 3D polar plot. This example requires scipy. In this example we use the mlab's mesh function: :func:`mayavi.mlab.mesh`. For plotting surfaces this is a very versatile function. The surfaces can be defined as functions of a 2D grid. For each spher...
s(phi) mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() # Represent spherical harmonics on the surface of the sphere for n in range(1, 6): for m in range(n): s = sph_harm(m, n, theta, phi).real mlab.mesh(x - m, y - n, z, scalars=s, colormap='jet'
) s[s < 0] *= 0.97 s /= s.max() mlab.mesh(s * x - m, s * y - n, s * z + 1.3, scalars=s, colormap='Spectral') mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25)) mlab.show()
bhdz/scalint
checks/ch_comparator.py
Python
apache-2.0
472
0.061441
from scalint.scalar_comparator import NativeComparator cmpr = NativeComparator() #simple checks for native py comparsion numerical and tuples assert cmpr(1,3) == cmpr.LT ass
ert cmpr(2,2) == cmpr.EQ assert cmpr(3,1) == cmpr.GT assert cmpr
( (1,1), (1,3) ) == cmpr.LT assert cmpr( (2,2), (2,2) ) == cmpr.EQ assert cmpr( (3,1), (2,1) ) == cmpr.GT assert cmpr( (1,) , (1,3) ) == cmpr.LT assert cmpr( (1,3), (1,3) ) == cmpr.EQ assert cmpr( (1,1,1), (1,1) ) == cmpr.GT
Joergen/zamboni
apps/paypal/tests/test_views.py
Python
bsd-3-clause
18,653
0.000322
# -*- coding: utf-8 -*- from decimal import Decimal import urllib from django import http, test from django.conf import settings from django.core import mail from mock import patch, Mock from nose.tools import eq_ from test_utils import RequestFactory import waffle import amo.tests from amo.urlresolvers import rever...
.objects.create(uuid=sample_purchase['tracking_id'], addon=self.addon) post_ipn.return_value = {'action': 'PAYMENT', 'status': 'OK', 'uuid': sample_purchase['tracking_id']} res = self.client.post(self.url, {}) eq_(res.content, ...
d=sample_purchase['tracking_id'], user=self.user) post_ipn.return_value = {'action': 'REFUND', 'amount': 'USD 1.00', 'status': 'OK', 'uuid': sample_purchase['tracking_id']} res = self.client.post(self.url, {}) eq_(res.content, 'Success!') def test_chargeback(self, post_ipn):...
dizzy54/ecommerce
src/products/models.py
Python
mit
5,256
0.000951
from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.text import slugify from django.utils.safestring import mark_safe # Create your models here. class ProductQuerySet(models.query.QuerySet): def active(self): return sel...
ductManager() class Meta: ordering = ["-title"] def __unicode__(self): # def __str__(self): return self.title def get_absolute_url(self): return reverse("product_detail", kwargs={"pk": self.pk}) def get_image_url(self): img = self.produc
timage_set.first() if img: return img.image.url return img class Variation(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20) sale_price = models.DecimalField(decimal_plac...
jkandasa/integration_tests
cfme/test_framework/appliance.py
Python
gpl-2.0
2,985
0.001675
import attr import pytest import warnings from fixtures import terminalreporter from cfme.utils import conf from cfme.utils.path import log_path from cfme.utils.appliance import ( load_appliances_from_config, stack, DummyAppliance, IPAppliance, ApplianceSummoningWarning) warnings.simplefilter('error', Ap...
if pytest.store.parallelizer_role != 'slave': with log_path.join('appliance_version').open('w') as appliance_version: appliance_version.write(self.held_appliance.ve
rsion.vstring)
freedryk/cloudtracker
doc/conf.py
Python
bsd-2-clause
7,125
0.006456
# -*- coding: utf-8 -*- # # cloudtracker documentation build configuration file, created by # sphinx-quickstart on Fri Aug 5 12:45:40 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
s (such as .. function:
:). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex...
chrys87/orca-beep
test/keystrokes/gtk3-demo/role_page_tab.py
Python
lgpl-2.1
1,415
0
#!/usr/bin/python """Test of page tab output.""" from macaroon.playback import * import utils sequence = MacroSequence() sequence.append(KeyComboAction("<Control>f")) sequence.append(TypeAction("Popovers")) sequence.append(KeyComboAction("Escape")) sequence.append(KeyComboAction("Down")) sequence.append(Key
ComboAction("Down")) sequence.append(KeyComboAction("<Shift>Right")) sequence.append(KeyComboAction("Down")) sequence.append(KeyComboAction("Return")) sequence.append(PauseAction(3000)) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Right")) sequence.append(utils.AssertPresentationAction...
dialog Page Setup page tab'", " VISIBLE: 'Page Setup page tab', cursor=1", "SPEECH OUTPUT: 'Page Setup page tab.'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_Enter")) sequence.append(utils.AssertPresentationAction( "2. Page Setup page tab Where Am I", ["...
joealcorn/berth.cc
berth/tests/webhooks/test_github.py
Python
mit
1,318
0.000759
import json from django.core.urlresolvers import reverse_lazy from exam import before, after, Exam from berth.celery import app as celery from berth.job import tasks from berth.project import constants from berth.utils.test import APITestCase noop = lambda *a, **kw: None class TestGithubWebhook(APITestCase): ...
f): data = json.loads(self.load_data('github/webhook.json')) project = self.create_project( name=data['repository']['name'], repo_identifier=data['repository']['id'], repo_source=constants.GITHUB, ) resp = self.client.post(self.endpoint, data, format...
_data('github/webhook.json')) resp = self.client.post(self.endpoint, data, format='json') assert resp.status_code == 404
indexofire/gork
src/gork/contrib/gauth/backends/permission_backend.py
Python
mit
1,878
0.000532
# -*- coding: utf-8 -*- from __future__ import with_statement from gauth.handlers import registry __all__ = ('PermissionBackend',) class PermissionBackend(object): """Authentication backend for cheking permissions This backend is used to check permissions. The permissions are handled with ``PermissionHa...
ser_obj, perm, obj=None)`` method of detected model's ``PermissionHandler`` will be used to cheking process. If no model was detected or no handler was registered, this backend does not touch that permission and return ``None`` to pass the permission checking process to downstream backends. """ ...
(self, username, password): """This backend is only for checking permission""" return None def has_perm(self, user_obj, perm, obj=None): """check permission""" # get permission handlers fot this perm cache_name = '_%s_cache' % perm if hasattr(self, cache_name): ...
pilhoo/EuroDriversWebSite
old/manage.py
Python
gpl-3.0
254
0
#!/usr/bin/env python import os import sys if __name__ ==
"__main__": os.environ.setdefault("DJANGO_SETTINGS
_MODULE", "EuroDrivers.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
julython/julython.org
july/settings.py
Python
mit
8,557
0
import os from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP from django.core.exceptions import SuspiciousOperation # Default settings that can be overwritten in secrets DEBUG = True SECRET_KEY = 'foobar' DATABASE_ENGINE = 'django.db.backends.sqlite3' DATABASE_NAME = 'julython.db' DATABASE_PASS...
ssociate_complete' SOCIAL_AUTH_PIPELINE = [ 'july.auth.social.social_auth_user', 'social_auth.backends.pipeline.user.get_username', 'social_auth.backends.pipeline.user.create_user',
'social_auth.backends.pipeline.social.associate_user', 'social_auth.backends.pipeline.social.load_extra_data', 'social_auth.backends.pipeline.user.update_user_details', ] # Just so we can use the same names for variables - why different social_auth?? GITHUB_APP_ID = GITHUB_CONSUMER_KEY GITHUB_API_SECRET = GIT...
pythononwheels/copow
uimodules/copow_ui_modules.py
Python
apache-2.0
3,272
0.005501
# # copow ui modules. # # see: http://tornado.readthedocs.org/en/latest/overview.html#ui-modules # # remark: wheneer I say "nice" in this module it's purely subjective to me ;) # import tornado.web import #A
PPNAME.config.settings class SimplePagination(tornado.web.UIModule): """
Renders a nice html selection list from given model entries Shows the specified model.attribute as selector. Default is _id (Which is probably something you want to change ;) """ def render(self, model=None, page=None, count=None): pages = count / atest.config.settings....
afisher1/volttron-applications
nrel/agents/RadioThermostatDriverRelayAgent/radiothermostatdriverrelay/settings.py
Python
bsd-3-clause
23
0
HEART
BEAT_PERIOD
= 20
sdss/marvin
python/marvin/web/controllers/__init__.py
Python
bsd-3-clause
2,791
0.000358
# !usr/bin/env python2 # -*- coding: utf-8 -*- # # Licensed under a 3-clause BSD license. # # @Author: Brian Cherinka # @Date: 2016-12-08 14:24:58 # @Last modified by: Brian Cherinka # @Last Modified time: 2018-07-13 18:21:26 from __future__ import print_function, division, absolute_import from flask_classful impo...
access() updateGlobalSession() self.base['error'] = None self._logged_in = current_session.get('loginre
ady', False) self._versions = update_allowed() self._endpoint = request.endpoint self._drpver, self._dapver, self._release = parseSession() # try to get a local version of the urlmap for the arg_validator if not av.urlmap: urlmap = build_routemap(current_app) ...
sanguillon/voprov
setup.py
Python
mit
1,855
0.001078
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages fr
om codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encod
ing='utf-8') as f: readme = f.read() requirements = [ 'prov>=1.5.3', ] test_requirements = [ 'pydot>=1.2.0' ] setup( name='voprov', version='0.0.2', description='A library for IVOA Provenance Data Model supporting PROV-JSON, ' 'PROV-XML and PROV-N', long_description=readme...
ethanrublee/ecto-release
test/scripts/test_If.py
Python
bsd-3-clause
2,018
0.004955
#!/usr/bin/env python # # Copyright (c) 2011, Willow Garage, 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 # n...
IRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, O
R PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import ecto import ecto_test def test...
danking/hail
hail/python/test/hail/matrixtable/test_grouped_matrix_table.py
Python
mit
12,704
0.007006
import unittest import hail as hl from ..helpers import * setUpModule = startTestHailContext tearDownModule = stopTestHailContext class Tests(unittest.TestCase): @staticmethod def get_groupable_matrix(): rt = hl.utils.range_matrix_table(n_rows=100, n_cols=20) rt = rt.annotate_globals(foo="f...
'row_idx'] + hl.agg.sum(mt['col_idx'])) # expression has to have global indices self.assertRaises(ExpressionException, b.aggregate_cols, bar=hl.agg.sum(mt['c'])) # aggregation scope is cols only - entry field self.assertRaises(ExpressionException, b.aggregate_cols, bar=hl.agg.sum(mt['row_idx'])) # aggre...
y - row field c = mt.group_rows_by(group5=(mt['group2']['a'] + 1)).aggregate_rows(x=hl.agg.count()) self.assertRaises(ExpressionException, c.aggregate_rows, x=hl.agg.count()) # duplicate field d = mt.group_cols_by(group5=(mt['group4']['a'] + 1)).aggregate_cols(x=hl.agg.count()) self.as...
welikecloud/bigtop
bigtop-packages/src/charm/mahout/layer-mahout/tests/01-mahout-test.py
Python
apache-2.0
2,393
0.000418
#!/usr/bin/env python3 # 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 "Lic...
imitations under the License. import unittest import amulet class TestDeploy(unittest.TestCase): """ Deployment and smoke test for Apache Bigtop Mahout.
""" @classmethod def setUpClass(cls): cls.d = amulet.Deployment(series='xenial') cls.d.add('mahout') cls.d.add('client', charm='hadoop-client') cls.d.add('namenode', charm='hadoop-namenode') cls.d.add('resourcemanager', charm='hadoop-resourcemanager') cls.d.add(...
xurichard/mysite
photos/views.py
Python
mit
753
0.022576
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import * import requests import json user_id = '139169754@N02' api_key = '
41dd3aff041c00c52febdef9786a9ca0' api_secret = '0f5a3b5047f760f7' def index(request): context = {} context['photos'] = [] method = 'flickr.people.getPublicPhotos' query = 'https://api.flickr.com/services/rest/?&method=%s&api_key=%s&user_id=%s&format=json&nojsoncallback=1'%(method, api_key, user_id) query += '&ex...
text) for link in response['photos']['photo']: context['photos'].append(str(link['url_z'])) return render(request, 'photos/index.html', context)
marksantesson/xmldump
test_utils.py
Python
apache-2.0
2,650
0.017736
# cd c:\Docs\Code\lawn # kr *.py -r -c "python manage.py test test_utils" import logging import os from django.test import TestCase from utils import LoggingFilterContext, TemporaryFileContext cla
ss TestLoggingFilter(TestCase): def test_filtering(self): calls = list() def test_fn(record): calls.append( record ) # Outter filters are checked first. with LoggingFilterContext( lambda record: False ): with LoggingFilterContext(
test_fn ): logging.error('pass') with LoggingFilterContext( lambda record: True ): with LoggingFilterContext( test_fn ): logging.error('fail') self.assertEquals( ['fail'], [x.msg for x in calls]) def test_filtering_annotate(self): calls = list() ...
ramon-astudillo/lxmls-toolkit
lxmls/sequences/bak/forward_backward.py
Python
mit
8,281
0.00157
import numpy as np # ---------- # Computes the forward backward trellis for a given sequence. # N - Length of sequence # H - Number of hidden states # Receives: # Node potentials (N,H) vector # Edge potentials (N-1,H,H) # # Emission probabilities: (length, num_states) array # Initial probabilities: (num_states) array...
os] += prob # forward[current_state,pos] *= node_potentials[current_state,pos] # # Backward loop # backward[:,N-1] = 1 # for pos in xrange(N-2,-1,-1): # for current_state in xrange(H): # prob = 0 # for next_state in xrange(H): #
back = backward[next_state,pos+1] # trans = transition_probs[next_state,current_state]; # observation = node_potentials[next_state,pos+1]; # prob += trans * observation * back; # backward[current_state,pos] = prob # # sanity_check_forward_backward(...
abhishek8gupta/sp17-i524
project/S17-IO-3017/code/projectearth/testfile.py
Python
apache-2.0
616
0.008117
import os class classFileWrite: fileobj = None directory = "./benchmark" fpath = directory + "/test.txt" de
f __init__(self): if not os.path.exists(self.directory): os.makedirs(self.directory) self.openfile() def openfile(self): self.fileobj = open(self.fpath, "a") def writeline(self): line = "=" * 60 line=line+"\n" self.fileobj.write(line)
def writelog(self,logstr=""): self.fileobj.seek(0,0) logstr = logstr+"\n" self.fileobj.write(logstr) def closefile(self): self.fileobj.close()
yackj/GameAnalysis
test/dominance_test.py
Python
apache-2.0
5,333
0
import json import numpy as np from gameanalysis import dominance from gameanalysis import gamegen from gameanalysis import gameio from gameanalysis import rsgame def test_weakly_dominated(): profiles = [ [2, 0], [1, 1], [0, 2], ] payoffs = [ [2, 0], [2, 1], ...
fs) wd = dominance.strictly_dominated(game, F
alse) assert np.all(wd == [False, False]) def test_never_best_response(): profiles = [ [2, 0], [1, 1], [0, 2], ] payoffs = [ [1, 0], [2, 2], [0, 1], ] game = rsgame.game(2, 2, profiles, payoffs) wd = dominance.never_best_response(game, False)...