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
anhstudios/swganh
data/scripts/templates/object/tangible/deed/event_perk/shared_fire_pit_deed.py
Python
mit
456
0.046053
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/deed/event_perk/shared_fire_pit_deed.iff" result.attribute_template...
result.stfName("event_perk","fire_pit_name") #### BEGIN MODIFICATIONS #### #### EN
D MODIFICATIONS #### return result
ppayter-cc/user-story-manager-ppayter-cc
smanager.py
Python
gpl-3.0
5,881
0.00204
import os import sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash # create our little application :) app = Flask(__name__) app.config.from_object(__name__) # Load default config and override config from an environment variable app.config.update(dict( DATABAS...
flash('please log in first') return redirect(url_for('login')) # entry form editing view @app
.route('/story/<int:story_id>') def edit_entry(story_id): if session.get('logged_in'): db = get_db() cur = db.execute('SELECT id, story_title, user_story, acceptance_criteria,\ business_value, estimation, status FROM entries ORDER BY id ASC') entries = cur.fetchall() for...
trove/trove-superalbums
superalbums/models.py
Python
mit
5,090
0.007662
from django.db import models from django.template.defaultfilters import slugify from tagging.fields import TagField from tagging.utils import parse_tag_input from django.contrib.auth.models import User from django.conf import settings import uuid,os import datetime # Create your models here. def slugify_uniquely(value...
while True: if suffix: potential = "-".join([base, str(suffix)]) if not model.objects.filter(**{slugfield: potential}).count(): return potential # we hit a conflicting slug, so bump the suffix & try again suf...
.%s" % (instance.uuid, ext) return os.path.join(settings.LOCAL_PHOTO_STORAGE_FOLDER, filename) class TrovePhoto(models.Model): user = models.ForeignKey(User) full_size = models.URLField(max_length=255) thumbnail = models.URLField(max_length=255) trove_id = models.CharField(max_length=200) ...
HudsonWerks/OLED-SSD1306
ssd1306/fonts/arial_narrow_16.py
Python
lgpl-3.0
52,921
0.243164
# coding=utf-8 # Module arial_narrow_16 # generated from Arial Narrow 12pt name = "Arial Narrow 16" start_char = '!' end_char = chr(127) char_height = 16 space_width = 8 gap_width = 2 bitmaps = ( # @0 '!' (1 pixels wide) 0x00, # 0x80, # O 0x80, # O 0x80, # O 0x80, # O 0x80, ...
O 0x84, # O O 0x84, # O O 0x84, # O O 0x48, # O O 0x30, # OO 0x00, # 0x00, # 0x00, # 0x00, # # @368 '7' (6 pixels wide) 0x00, # 0xFC, # OOOOOO 0x04, # O 0x08, # O 0x10, # O
0x10, # O 0x20, # O 0x20, # O 0x20, # O 0x40, # O 0x40, # O 0x40, # O 0x00, # 0x00, # 0x00, # 0x00, # # @384 '8' (6 pixels wide) 0x00, # 0x30, # OO 0x48, # O O 0x84, # O O 0...
FrodeSolheim/fs-uae-launcher
arcade/ui/event.py
Python
gpl-2.0
21,760
0.000046
from functools import lru_cache from fscore.system import System from fsgamesys.util import sdl2 from fsui.qt import QEvent, Qt class KeySym: def __init__(self): self.sym = 0 class Key: def __init__(self): self.keysym = KeySym() class Event: def __init__(self): self.type = 0 ...
event["pos"] = x, y return event def get_key(ev): print("Qt key:", ev.key(), int(ev.modifiers()), Qt.KeypadModifier) if System.macos: # FIXME: TODO: CHECK
# if ev.key() == Qt.Key_Meta: # print("Control key, native virtual code:", ev.nativeVirtualCode()) # elif ev.key() == Qt.Key_Shift: pass else: if ev.key() == Qt.Key_Control: print("Control key, native scan code:", ev.nativeScanCode()) if ev.nativeScanCod...
Aptitudetech/ERPNext
erpnext/setup/utils.py
Python
cc0-1.0
4,104
0.033138
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt from frappe.utils import get_datetime_str, nowdate def get_root_of(doc
type): """Get root element of a DocType with a tree structure""" result = frappe.db.sql_list("""select name from `tab%s` where lft=1 and rgt=(select max(rgt) from `tab%s` where docstatus < 2)""" % (doctype, doctype)) return result[0] if result else None def get_ancestors_of(doctype, name): """Get ancestor elem...
pe.db.sql_list("""select name from `tab%s` where lft<%s and rgt>%s order by lft desc""" % (doctype, "%s", "%s"), (lft, rgt)) return result or [] def before_tests(): frappe.clear_cache() # complete setup if missing from frappe.desk.page.setup_wizard.setup_wizard import setup_complete if not frappe.get_list("Comp...
campbellC/introToPython
session4ObjectsLesson2/carsGame/newCar.py
Python
mit
532
0.005639
from vehicle import Vehicle class Car(Vehicle): """A class tha models a simple car""" def printMe(self):
speedString = str(self.currentSpeed) + ' miles an hour' gearString = {0: 'p', 1:'first', 2: 's
econd'}[self.gear] + ' gear' print "I am a " + self.make + ' travelling at ' + speedString + " in " + gearString if __name__ == '__main__': ford = Car("ford", 15) ford.printMe() ford.changeGear(2) ford.accelerate(10) ford.printMe()
Esri/public-transit-tools
deprecated-tools/better-bus-buffers/BBB_CountTripsAtStops.py
Python
apache-2.0
5,373
0.005956
############################################################################ ## Tool name: BetterBusBuffers - Count Trips at Stops ## Created by: Melinda Morang, Esri, mmorang@esri.com ## Last updated: 30 November 2017 ############################################################################ ''' BetterBusBuffers - C...
gement.AddField(outStops, "NumTripsPerHr", "DOUBLE") arcpy.management.AddField(outStops, "MaxWaitTime", "SHORT") except: arcpy.AddError("Error creating feature class of GTFS stops.") raise #----- Query the GTFS data to count the trips at each stop ----- ...
[[trip_id, stop_time]]} for our time window stoptimedict = BBB_SharedFunctions.CountTripsAtStops(day, start_sec, end_sec, BBB_SharedFunctions.CleanUpDepOrArr(DepOrArrChoice), Specific) except: arcpy.AddError("Error counting arrivals or departures at stop during time window.") ...
p4lang/p4c
tools/driver/p4c_src/driver.py
Python
apache-2.0
11,889
0.004121
# Copyright 2013-present Barefoot Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
target + '-' + arch self._commands = {} self._commandsEnabled = []
self._preCmds = {} self._postCmds = {} self._argParser = argParser self._argGroup = None # options self._dry_run = False self._output_directory = "./" self._source_filename = None self._source_basename = None self._verbose = False self._run...
ttesileanu/twostagelearning
simulation.py
Python
mit
6,696
0.007766
""" Define a simple framework for time-evolving a set of arbitrary agents and monitoring their evolution. """ import numpy as np def int_r(f): """ Convert to nearest integer. """ return int(np.round(f)) class Simulation(object): """ A class that manages the evolution of a set of agents. This is a simple o...
ro()[0] n = len(idxs) if n > 0: self.t.extend([t]*n) self.i.extend(idxs) class StateMonitor(object): """ A class that can be used to monitor the time evolution of an attribute of an agent
. The `order` attribute for this class is set to 1 by default, so that it gets executed after all the usual agents are executed. This means that it stores the values of the state variables at the end of each time step. Attributes ---------- t: array Array of times where state has been monitored. ...
levilucio/SyVOLT
UMLRT2Kiltera_MM/transformation/handbuilt/HCompositeState2ProcDef.py
Python
mit
14,159
0.017374
from core.himesis import Himesis import uuid class HCompositeState2ProcDef(Himesis): def __init__(self): """ C
reates the himesis graph representing the DSLTrans rule CompositeState2ProcDef. """ # Flag this instance as compiled
now self.is_compiled = True super(HCompositeState2ProcDef, self).__init__(name='HCompositeState2ProcDef', num_nodes=0, edges=[]) # Set the graph attributes self["mm__"] = ['HimesisMM'] self["name"] = """CompositeState2ProcDef""" self["G...
pa-pyrus/papatcher
papatcher.py
Python
mit
17,605
0.000114
#!/usr/bin/env python3 # vim:fileencoding=utf-8:ts=8:et:sw=4:sts=4:tw=79 """ papatcher.py: simple python PA patcher Copyright (c) 2014 Pyrus <pyrus@coffee-break.at> See the file LICENSE for copying permission. """ from argparse import ArgumentParser from concurrent import futures from contextlib import contextmanage...
self.connection = HTTPSConnection(UBERNET_HOST, context=ssl_context) self.threads = threads self.ratelimit = ratelimit def login(self): """ Login to UberNet and store a session ticket if successful. """ # return immediat...
lf, "_session"): return True # otherwise request a new one headers = {"Content-Type": "application/json;charset=utf-8"} self.connection.request("POST", "/GC/Authenticate", headers=headers, body=self.credentials) response = self.connection.getr...
DooMMasteR/hitview
testserver.py
Python
mit
432
0.016204
from Sim
pleWebSocketServer import WebSocket, SimpleWebSocketServer class SimpleEcho(WebSocket): def handleMessage(self): # echo message back to client print(self.data) self.sendMessage(self.data) def handleConnected(self): print self.address, 'connected' def handleClose(self): p...
losed' server = SimpleWebSocketServer('', 8000, SimpleEcho) server.serveforever()
lonnen/socorro
webapp-django/crashstats/cron/migrations/0004_auto_20181214_1951.py
Python
mpl-2.0
4,301
0.001395
# Generated by Django 1.11.16 on 2018-12-14 19:51 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.db import migrations, models class Migration(migration...
help_text="the crontabber app this log entry is for", max_length=100 ), ), migrations.AlterField( model_name="log", name="duratio
n", field=models.FloatField(help_text="duration in seconds"), ), migrations.AlterField( model_name="log", name="exc_traceback", field=models.TextField( blank=True, help_text="the exc traceback of an error if any", null=True ), ...
anthraxx/arch-security-tracker
tracker/view/admin.py
Python
mit
5,628
0.001955
from flask import flash from flask import redirect from flask import render_template from flask_login import current_user from flask_login import login_required from config import TRACKER_PASSWORD_LENGTH_MAX from config import TRACKER_PASSWORD_LENGTH_MIN from tracker import db from tracker import tracker from tracker....
mport administrator_required from tracker.user import hash_password from tracker.user import random_string from tracker.user import user_invalidate from tracker.view.error import forbidden from tracker.view.error import not_found @tracker.route('/admin'
, methods=['GET', 'POST']) @tracker.route('/user', methods=['GET', 'POST']) @login_required def list_user(): users = User.query.order_by(User.name).all() users = sorted(users, key=lambda u: u.name) if not current_user.role.is_administrator: masked = [] for user in users: guest =...
armandobs14/rdflib
test/test_bnode_ncname.py
Python
bsd-3-clause
2,632
0.009502
# -*- coding: utf-8 -*- import re import sys try: from hashlib import md5 except ImportError: from md5 import md5 from rdflib.py3compat import format_doctest_out try: from uuid import uuid4 except ImportError: def uuid4(): """ Generates a uuid on behalf of Python 2.4 """ ...
preseed = '' # Have doubts about this. random.seed will just hash the string random.seed('%s%s%s' % (preseed, os.getpid(), time.time())) del preseed t = lo
ng( time.time() * 1000.0 ) r = long( random.random()*100000000000000000L ) try: a = socket.gethostbyname( socket.gethostname() ) except: # if we can't get a network address, just imagine one a = random.random()*100000000000000000L strdata = str(t)+' '+...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/python/ops/gen_functional_ops.py
Python
bsd-2-clause
2,756
0.003991
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. """ import collections as _collections from google.protobuf import text_format as _text_format from tensorflow.core.framework import op_def_pb2 as _op_def_pb2 # Needed to trigger the call to _set_call_cpp_shape_fn. from tensorfl...
fLibrary() op_def_lib.add_op_list(op_list) return op_def_lib _InitOpDefLibrary.op_list_ascii = """op { name: "SymbolicGradient" input_arg { name: "input" type_list_attr: "Tin" } output_arg { name: "output" type_list_attr: "Tout" } attr { name: "Tin
" type: "list(type)" has_minimum: true minimum: 1 } attr { name: "Tout" type: "list(type)" has_minimum: true minimum: 1 } attr { name: "f" type: "func" } } """ _op_def_lib = _InitOpDefLibrary()
Necromunger/unitystation
Tools/DMI_splitter_and_meta_maker/duplicate_name_renamer.py
Python
agpl-3.0
1,520
0.023026
import os from PIL import Image #Requires pillow import time #import json import shutil #Requires shutil import simplejson from decimal import Decimal #python 3 path = 'textures' #E.G The name of a folder everything is in Just set it to bypass The Manual input if not path: path = input('''The name of the folde...
h.basename(root)) old_file = os.path.join(root, name) new_file = os.path.join(root,os.path.basename(root)+ "_" + name) os.rename(old_file,new_file) #print(new_file) #else: #Name_store.add(name)
print(AID) print("--- %s seconds ---" % (time.time() - start_time)) #Total time
phw/weblate
weblate/formats/tests/test_external.py
Python
gpl-3.0
1,836
0.000546
# # Copyright © 2012 - 2021 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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 Lice...
.tests.test_formats import AutoFormatTest from weblate.trans.tests.utils import get_test_file XLSX_FILE = get_test_file("cs-mono.xlsx") class XlsxFormatTest(AutoFormatTest): FORMAT = XlsxFormat FILE = XLSX_FILE MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" EXT = "xlsx" ...
translations.xlsx" FIND = "HELLO" FIND_MATCH = "Hello, world!\r\n" MATCH = b"PK" NEW_UNIT_MATCH = b"PK" BASE = XLSX_FILE EXPECTED_FLAGS = "" def assert_same(self, newdata, testdata): newworkbook = load_workbook(BytesIO(newdata)) testworkbook = load_workbook(BytesIO(testdata)...
v0devil/jltom
ltc/administrator/urls.py
Python
mit
734
0
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.administrator_page), url(r'^new_jd/$', views.new_jd_page), url(r'^test_data/refresh/$', views.test_data_refresh), url(r'^jd/(?P<jd_id>\d+)/delete/', views.delete_jd), url(r'^jd/(?P<jd_
id>\d+)/create/$', views.create_jd), url(r'^new_ssh_key/$', views.new_ssh_key_page), url(r'^ssh_key/(?P<ssh_key_id>\d+)/delete/', views.delete_ssh_key), url(r'^ssh_key/(?P<ssh_key_id>\d+)/create/$', views.create_ssh_key), url(r'^new_parameter/$', views.new_parameter_page), url(r'^parameters/(?P<para...
rs/(?P<param_id>\d+)/create/$', views.create_parameter), ]
rfleschenberg/django-shop
shop/rest/serializers.py
Python
bsd-3-clause
14,995
0.003401
# -*- coding: utf-8 -*- from __future__ import unicode_literals from collections import OrderedDict from django.core import exceptions from django.core.cache import cache from django.db import models from django.template import RequestContext from django.template import TemplateDoesNotExist from django.template.loader...
help_text="The product's primary key") extra = serializers.DictField(read_only=True) def __init__(self, instance=None, data=empty, **kwargs): context = kwargs.get('context', {}) if 'product' in context: instance = self.get_instance(context, data, kwargs) if data == empty...
nternal_value(data['quantity']) instance.setdefault('quantity', quantity) instance.setdefault('subtotal', instance['quantity'] * instance['unit_price']) super(AddToCartSerializer, self).__init__(instance, data, context=context) else: super(AddToCartSerializer, sel...
dhermes/gcloud-python
logging/tests/unit/test_sink.py
Python
apache-2.0
12,160
0.001069
# Copyright 2016 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
_Client(project=self.PROJECT) sink = self._make_one( self.SINK_NAME, self.FILTER, self.DESTINATION_URI, client=client1 ) api = client2.sinks_api = _DummySinksAPI() api._sink_create_response = { "name": self.SINK_NAME, "filter": self.FILTER, ...
ertEqual(sink.name, self.SINK_NAME) self.assertEqual(sink.filter_, self.FILTER) self.assertEqual(sink.destination, self.DESTINATION_URI) self.assertEqual(sink.writer_identity, self.WRITER_IDENTITY) self.assertEqual( api._sink_create_called_with, (self.PROJECT, sel...
rcfduarte/nmsat
projects/examples/parameters/noise_driven_dynamics.py
Python
gpl-2.0
6,567
0.00335
__author__ = 'duarte' import sys from preset import * import numpy as np """ spike_noise_input - standard network setup, driven with noisy, Poissonian input - quantify and set population state - run with noise_driven_dynamics in computations - debug with noise_driven_dynamics script """ run = 'local' data_label = 'ex...
e, # perform time-resolved analysis } } # ################################################################################################################## # RETURN dictionary of Parameters dictionaries # =========================================================================================...
neuron_pars), ('net_pars', net_pars), ('encoding_pars', encoding_pars), ('connection_pars', connection_pars), ('analysis_pars', analysis_pars)]) # ######################################################################################################...
Pythagorists/pypiwik
tests/__init__.py
Python
mit
676
0
import json import unittest import responses class PywikTestCase(unittest.TestCase): def add_
fake_response(self, module, method, value, http_method='get', status=200): responses.add( getattr(responses, http_method.upper()), 'http://example.test/?' 'module={module}' '&method={module}.{method}' '&format=json' ...
content_type='application/json', status=200, )
Azure/azure-sdk-for-python
sdk/storage/azure-storage-blob/samples/blob_samples_common_async.py
Python
mit
9,540
0.003354
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT
License. See License.txt in the project root for # license infor
mation. # -------------------------------------------------------------------------- """ FILE: blob_samples_common_async.py DESCRIPTION: This sample demonstrates common blob operations including creating snapshots, soft deleteing, undeleting blobs, batch deleting blobs and acquiring lease. USAGE: python bl...
x75/smq
experiments/conf/default.py
Python
mit
2,364
0.002538
""" Default experiment for clean
smp Should be self-contained requiring now external packages or processes. Robot: Point mass World: open linear (1D) space Task: null task: task performance is always null no matter what Brain: null brain: just output null Loss: 0 """ import time from smq.utils import make_column_names_numbered from smq.worlds i...
k from smq.brains import NullBrain # local variables for re-use numsteps = 1000 motors = 1 # using dict convention seemed to be the best over yaml and friends conf = { # first level corresponds to experiment "numsteps": numsteps, "id": "default-%s" % (time.strftime("%Y%m%d-%H%M%S")), # these are arr...
mozilla/elmo
apps/tinder/templatetags/build_extras.py
Python
mpl-2.0
4,246
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. '''Django template filters to be used to display builds. ''' from __future__ import absolute_import, division from __fut...
oescape: return conditional_escape(input) return input if build_or_step is None: return mark_safe("&nbsp;") if isinstance(build_or_step, Change): # blame column change = build_or_step fmt = ('<a href="' + reverse(tinder.views.builds_for_change) ...
) if isinstance(build_or_step, Build): fmt = '<a href="%s" title="%s">Build %d</a><br/>%s %s' build = build_or_step b_url = reverse('tinder-showbuild', args=[build.builder.name, build.buildnumber]) rv = fmt % (b_url, build.starttime.isoformat(), build.build...
LLNL/spack
var/spack/repos/builtin/packages/ossp-uuid/package.py
Python
lgpl-2.1
970
0.002062
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Sp
ack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class OsspUuid(AutotoolsPackage): """OSSP uuid is
a ISO-C:1999 application programming interface (API) and corresponding command line interface (CLI) for the generation of DCE 1.1, ISO/IEC 11578:1996 and RFC 4122 compliant Universally Unique Identifier (UUID).""" homepage = "http://www.ossp.org/pkg/lib/uuid" url = "https://www.mirrorservice.org/s...
planbcoin/planbcoin
test/functional/test_framework/blocktools.py
Python
mit
3,929
0.004836
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The PlanBcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Utilities for manipulating blocks and transactions.""" from .mininode import * from .script import CScrip...
()): tx = CTransaction() assert(n < len(prevtx.vout)) tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), sig, 0xffffffff)) tx.vout.append(CTxOut(value, scriptPubKey)) tx.calc_sha256() return tx def get_legacy_sigopcount_block(block, fAccurate=True): count = 0 for tx in block.
vtx: count += get_legacy_sigopcount_tx(tx, fAccurate) return count def get_legacy_sigopcount_tx(tx, fAccurate=True): count = 0 for i in tx.vout: count += i.scriptPubKey.GetSigOpCount(fAccurate) for j in tx.vin: # scriptSig might be of type bytes, so convert to CScript for the mo...
flumotion-mirror/flumotion
flumotion/common/planet.py
Python
lgpl-2.1
13,121
0.00061
# -*- Mode: Python; -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Pu...
anagerAtmosphereState} - flows (list): list of L{ManagerFlowState} """ # FIXME: why is there a 'p
arent' key ? def __init__(self): flavors.StateCacheable.__init__(self) self.addKey('name') self.addKey('version') self.addKey('parent') self.addKey('manager') self.addKey('atmosphere') self.addListKey('flows') self.addDictKey('messages') # we...
pdebuyl/cg_md_polymerization
code/chain_h5md.py
Python
bsd-3-clause
4,743
0.006747
# Pierre de Buyl 2014 # This file is licensed under the modified BSD license import espressopp from espressopp import Real3D import pyh5md import numpy as np def DumpH5MD(filename, system, integrator, author, author_email=None, edges=None, edges_time=False, n_states=None): espressopp.Version().info() f = pyh5...
periodic', 'periodic'], edges=edges) f.NPart = espressopp.analysis.NPart(system).compute() f.observable('particle_number', data=int(f.NPart), time=False) f.f['observables'].attrs['dimension']=3 obs_dict = {} f.n_states = n_states state_tuple = (('statecount', (n_states,), np.int32),) if n_states...
gy', (), np.float64), ('pressure', (), np.float64), ('pressure_tensor', (6,), np.float64), ('potential_energy', (), np.float64),('internal_energy', (), np.float64), ('lennard_jones', (), np.float64), ('mirror_lennard_jones', (), np.float64), ) + state_tuple: o...
paramono/feincms_simplegallery
setup.py
Python
bsd-3-clause
1,307
0
#!/usr/bin/env python3 import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name=...
b.com/paramono/feincms_simplegallery', author='Alexander Paramonov', author_email='alex@paramono.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', # example license ...
'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Stratoscale/dirbalak
py/dirbalak/dependencygraph.py
Python
apache-2.0
2,973
0.001009
from dirbalak import graph from dirbalak import repomirrorcache from dirbalak import describetime from upseto import gitwrapper class DependencyGraph: _CONTINUOUS_INTEGRATION_VIOLATION_TIME = 14 * 24 * 60 * 60 def __init__(sel
f, dependencies, getNodeAttributesCallback): self._dependencies = dependencies self._getNodeAttributesCallback = getNodeAttributesCallback self._cachedGraph = None def renderText(self): return "\n".join([str(d) for d in self._dependencies]) + \ "\n\n" + self.m
akeGraph().renderAsTreeText() def makeGraph(self): if self._cachedGraph is None: self._cachedGraph = self._makeGraph() return self._cachedGraph def _makeGraph(self): graphInstance = graph.Graph(dict(ranksep=0.7)) for dep in self._dependencies: self._addN...
tonyldo/palestra_iot
main.py
Python
mit
1,887
0.005829
from umqtt.simple import MQTTClient from machine import Pin import ubinascii import machine import time import network # Default MQTT server to connect to SERVER = "m11.cloudmqtt.com" PORT = 15034 CLIENT_ID = ubinascii.hexlify(machine.unique_id()) TOPIC = b"hello/world" USER = "oyqmvonl" PASSWORD = "eCPIJkxVFWBU" ...
y: print('check
mensage...') c.check_msg() except: print('error on check mensage...') while 1: try: print('try reconnect...') c.connect(False) break except: ...
scottpurdy/nupic.core
bindings/py/tests/network_test.py
Python
agpl-3.0
3,782
0.00899
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2017, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
getByName( SerializationTestPyRegion.__name__) self.assertEqual(destRegion.getParameterUIn
t32("dataWidth"), 128) self.assertEqual(destRegion.getParameterUInt32("randomSeed"), 99) finally: engine.Network.unregisterPyRegion(SerializationTestPyRegion.__name__) def testSimpleTwoRegionNetworkIntrospection(self): # Create Network instance network = engine.Network() # Add two Test...
mlflow/mlflow
tests/spark/autologging/datasource/test_spark_datasource_autologging_missing_jar.py
Python
apache-2.0
512
0.001953
import pytest
import mlflow.spark from mlflow.exceptions import MlflowException from tests.spark.autologging.utils import _get_or_create_spark_session @pytest.mark.large def test_enabling_autologging_throws_for_missing_jar(): # pylint: disable=unused-argument spark_session = _get_or_create_spark_session(jars="") try:...
mlflow.spark.autolog() finally: spark_session.stop()
amorphic/braubuddy
braubuddy/thermostat/__init__.py
Python
bsd-3-clause
150
0
''' Braubuddy Thermostat. ''' from braubuddy.thermostat.base import IThermostat from braubuddy.thermostat.simpleranged import SimpleRangedThermost
at
johnlee175/LogcatFileReader
examples/simple_utils.py
Python
apache-2.0
6,336
0.000947
#!/usr/bin/env python import urllib import urllib2 import re import os import sys import time # upload('http://www.mywebsite.com:8080/upload.php', {}, 'file', os.path.join('/home/john/', 'a.txt')) def upload(http_url, form_params, file_item_name, file_path): boundary = '-----------------%s' % hex(int(time.time()...
': return 'macosx' elif sys.platform == 'linux2': return 'linux' elif sys.platform.find('win') >= 0: return 'windows' else: return '' def binary(name): if os.name == 'posix': return './' + name elif os.name == 'nt': return name + '.exe' else:
return name
BD2KGenomics/toil-old
src/toil/test/__init__.py
Python
mit
1,203
0.001663
import logging import os import shlex import unittest import sys from toil.common import toilPackageDirPath from toil.lib.bioio import getBasi
cOptionParser, parseSuiteTestOptions log = logging.g
etLogger(__name__) class ToilTest(unittest.TestCase): """ A common base class for our tests. Please have every test case directly or indirectly inherit this one. """ orig_sys_argv = None def getScriptPath(self, script_name): return os.path.join(toilPackageDirPath(), 'utils', script_name ...
asenovm/book-search-server
crawler/chitanka_crawler_get_categories.py
Python
mit
548
0.007299
import requ
ests import time import os import sqlite3 def main(): conn = sqlite3.connect('chitanka.db') c = conn.cursor() r = reque
sts.get('http://www.chitanka.info/books') ind = 0 ind = r.text.find('books/category/', ind) while ind != -1: ind = ind + 15 print r.text[ind:r.text.find('"', ind)] c.execute("insert into categories values ('"+r.text[ind:r.text.find('"', ind)]+"')") ind = r.text.find('books/ca...
barche/k3d
tests/mesh/mesh.modifier.ExtrudeFaces.py
Python
gpl-2.0
639
0.007825
#python import k3d import testing setup = testing.setup_mesh_modifier_test("PolyGrid", "ExtrudeFaces") setup.source.
rows = 3 setup.source.columns = 3 selection = k3d.geometry.selection.create(0) face_selection = k3d.geometry.primitive_selection.create(selection, k3d.selection.type.FACE) k3d.geometry.primitive_selection.append(face_selection, 4, 5, 1) setup.modifier.mesh_selection = selection setup.modifier.distance = 5 testing.re...
mesh(setup.document, setup.modifier.get_property("output_mesh"), "mesh.modifier.ExtrudeFaces", 2)
quattor/aquilon
lib/aquilon/worker/formats/location.py
Python
apache-2.0
4,816
0.001246
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008-2014,2016-2019 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may o...
edded=True, indirect_attrs=True): skeleton.name = loc.name # Backwards compatibility if loc.location_type == "organization": skeleton.location_type = "company" else: skeleton.location_type = loc.location_type skeleton.fullname = loc.fullname if isi...
skeleton.col = loc.rack_column if hasattr(loc, "timezone"): skeleton.timezone = loc.timezone if hasattr(loc, "uri") and loc.uri: skeleton.uri = loc.uri if indirect_attrs: for p in loc.parents: parent = skeleton.parents.add() ...
Stranger6667/postmarker
test/test_exceptions.py
Python
mit
354
0.002825
import pytest from po
stmarker.exceptions import ClientError CASSETTE_NAME = "exceptions" def test_raise(postmark): with pytest.raises(ClientError) as exc: postmark.templates.get(123) assert str(exc.value) == "[1101] The 'TemplateId' associated with this request is not valid or was not found." assert exc.value.error_c...
101
RaphaelArkadyMeyer/LiveCoding
Student CL/setup.py
Python
mit
338
0.002959
from setuptools import setup se
tup( name='testcl-click', version='1.0', py_modules=['testcl'], include_package_data=True, install_requires=[ 'click', # Colorama is only required for Windows. 'colorama', ], entry_points=''' [console_scripts] testcl=testcl:cli ''',
)
jorgenkg/python-neural-network
nimblenet/learning_algorithms/resilient_backpropagation.py
Python
bsd-2-clause
6,265
0.029848
from ..tools import add_bias, confirm from ..activation_functions import softmax_function from ..cost_functions import softmax_neg_loss import numpy as np def resilient_backpropagation(network, trainingset, testset, cost_function, ERROR_LIMIT=1e-3, max_iterations = (), weight_step_max = 50., weight_step_min = 0., sta...
testset ] ) # Storing the current / previous weight step size weight_step = [ np.full( weight_layer.shape, start_step ) for weight_layer in network.weights ] # Storing the current / previous weight update dW = [ np.ones(shape=weight_layer.shape) for weig...
work.weights ) # Storing the previous error measurement prev_error = ( ) # inf input_signals, derivatives = network.update( training_data, trace=True ) out = input_signals[-1] cost_derivative = cost_function(out,...
snnn/tensorflow
tensorflow/contrib/lookup/lookup_ops_test.py
Python
apache-2.0
98,640
0.012024
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
values = constant_op.constant([0, 1, 2], dtypes.int64) table = lookup.HashTable( lookup.KeyValueTensorInitializer(keys, values), default_val) table.init.run() self.assertAllEqual(3, table.size().eval()) input_string = constant_op.constant( [["brain", "salad"], ["tank", "t...
llEqual([[0, 1], [-1, -1]], result) def testHashTableInitWithPythonArrays(self): with self.cached_session(): default_val = -1 keys = ["brain", "salad", "surgery"] values = [0, 1, 2] table = lookup.HashTable( lookup.KeyValueTensorInitializer( keys, values, value_dty...
iwaseyusuke/ryu
ryu/services/protocols/bgp/net_ctrl.py
Python
apache-2.0
15,431
0
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
'body!') return self._packer.pack([RPC_MSG_RESPONSE, msgid, None, result]) def create_notification(self, method, params): return self._packer.pack([RPC_MSG_NOTIFY, method, params]) def feed_and_get_messages(self, data): self._unpacker.feed(data) messages = [] for m...
in self._unpacker: messages.append(msg) return messages def feed_and_get_first_message(self, data): self._unpacker.feed(data) for msg in self._unpacker: return msg def _send_error_response(self, request, err_msg): rpc_msg = self.create_error_response(req...
alejandroautalan/pygubu
pygubu/stockimage.py
Python
mit
6,818
0.000147
# encoding: utf8 __all__ = ['StockImage', 'StockImageException', 'TK_IMAGE_FORMATS'] import logging import os import tkinter as tk logger = logging.getLogger(__name__) class StockImageException(Exception): pass BITMAP_TEMPLATE = '@{0}' TK_BITMAP_FORMATS = ['.xbm'] TK_PHOTO_FORMATS = ['.gif', '.pgm', '.ppm']...
ge using key""" if key in cls._stock: logger.info('Warning, replacing resource {0}', key) cls._stock[key] = {'type': 'created', 'image': image} logger.info('%s registered as %s', 'data', key) @classmethod def is_registered(cls, key): return key in cls._stock @c...
: """List files from dir_path and register images with filename as key (without extension) :param str dir_path: path to search for images. :param str prefix: Additionaly a prefix for the key can be provided, so the resulting key will be prefix + filename :param i...
jeremiedecock/snippets
python/tkinter/python3/animation_canvas_update_shapes_instances_coords.py
Python
mit
2,095
0.001433
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # 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 witho...
root.after(TIME_STEP_MS, update_canvas) # Schedule event in TIME_STEP_MS milli second root.after(TIME
_STEP_MS, update_canvas) root.mainloop()
lehmannro/translate
storage/test_ts2.py
Python
gpl-2.0
4,738
0.002118
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008-2009 Zuza Software Foundation # # This file is part of the Translate Toolkit. # # 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; e...
eunit("Concept") tsunit.target = "Konsep" newfile = ts.tsfile.parsestring(str(tsfile)) print str(tsfile) assert newfile.findunit("Concept").target == "Konsep" def test_plurals(self): """Test basic plurals""" tsfile = ts.tsfile() tsunit = tsfile.addsourceunit(...
tsunit.target = [u"Leêr", u"Leêrs"] newfile = ts.tsfile.parsestring(str(tsfile)) print str(tsfile) checkunit = newfile.findunit("File(s)") assert checkunit.target == [u"Leêr", u"Leêrs"] assert checkunit.hasplural() def test_language(self): """Check that we can get a...
obi-two/Rebelion
data/scripts/templates/object/tangible/lair/perlek/shared_lair_perlek_grassland.py
Python
mit
460
0.047826
#### NOTICE: THIS
FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible
() result.template = "object/tangible/lair/perlek/shared_lair_perlek_grassland.iff" result.attribute_template_id = -1 result.stfName("lair_n","perlek_grassland") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
simium/PyThermal
thermal_image_generator.py
Python
gpl-2.0
1,461
0
#!/usr/bin/python import Image import time import datetime import csv import thermal_config as tcfg millis_at_s
tart = int(round(time.time() * 1000)) temp_data = list(csv.reader(open(tcfg.files['csv']))) img = Image.new('RGB', (tcfg.fov['horizontal'], tcfg.fov['vertical']), "black") pixels = img.load() print 'Processing data: WxH = %dx%d pixels...' \ % (tcfg.fov['horizontal'], tcfg.fov['vertical']) for i in range(tcfg....
) if t > len(tcfg.temperatures)-1: pixels[j, i] = (255, 255, 255) else: if tcfg.options['bw'] is True: m = tcfg.temperature_map(t, 0, 65, 255, 0) r = m g = m b = m else: r = tcfg.temperatu...
zstackorg/zstack-woodpecker
integrationtest/vm/virtualrouter/vip_qos/test_vrouter_vip_port_qos_multi_crt.py
Python
apache-2.0
1,199
0.00417
''' New Integration Test for vip qos. @author: Legion ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state test_stub = test_lib.lib_get_test_stub() test_obj_dict = test_state.TestStateDict() qos = test_stub.VIPQOS() def test...
qos.del_vip_qos() port = test_stub.gen_random_port() qos.set_vip_qos(21, 25, port, port) qos.check_outbound_bandwidth() qos.check_inbound_bandwidth() qos.vip.delete() test_obj_dict.rm_vm(qos.vm) test_util.test_pass('VRouter Network VIP Port QoS Multi Creation Deletion
Test Success') def env_recover(): if qos.vm: qos.vm.destroy() if qos.vip: qos.vip.delete() #Will be called only if exception happens in test(). def error_cleanup(): global test_obj_dict test_lib.lib_error_cleanup(test_obj_dict)
JacekKarnasiewicz/HomePage
apps/search_app/views.py
Python
mit
215
0.013953
from d
jango.shortcuts import render from .models import Applications def search_app(request): ctx = {'applications': Applications.objects.filter(visible=True)} return render(request, 'search_app/home.html', ctx
)
emakis/erpnext
erpnext/accounts/doctype/asset/asset.py
Python
gpl-3.0
10,030
0.024526
# -*- coding: utf-8 -*- # Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, add_months, cint, nowdate, getdate from frappe.model.document import Do...
ils(self.item_code) for field, value in item_details.items(
): if not self.get(field): self.set(field, value) self.value_after_depreciation = (flt(self.gross_purchase_amount) - flt(self.opening_accumulated_depreciation)) def validate_asset_values(self): if flt(self.expected_value_after_useful_life) >= flt(self.gross_purchase_amount): frappe.throw(_("Expect...
ChameleonCloud/horizon
openstack_dashboard/dashboards/admin/metadata_defs/forms.py
Python
apache-2.0
6,611
0
# # (c) Cop
yright 2014 Hewlett-Packard Development Company, L.P. # # Licens
ed 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 ...
timtammittee/thorns
thorns/__init__.py
Python
gpl-3.0
1,184
0
"""Spike analysis software. """ from __future__ import division, print_function, absolute_import __author__ = "Marek Rudnicki" __version__ = "0.7.2" import os if 'THpdb' in os.environ: import pdb import sys import traceback def info(type, value, tb): traceback.print_exception(type, value...
level = os.environ['THlog'].upper() logger = logging.getLogger('thorns') logger.setLevel(level) import thorns.util import thorns.waves import thorns.io from thorns.spikes import ( make_trains, trains_to_array, accumulate, select_trains, trim, fold, ) fro
m thorns.stats import ( get_duration, shuffled_autocorrelogram, correlation_index, firing_rate, psth, isih, entrainment, vector_strength, spike_count, period_histogram ) from thorns.plotting import ( plot_raster, plot_psth, plot_isih, plot_neurogram, plot_sac...
mark-me/Pi-Jukebox
venv/Lib/site-packages/pygame/tests/joystick_test.py
Python
agpl-3.0
3,254
0.031346
import unittest class JoystickTypeTest(unittest.TestCase): def todo_test_Joystick(self): # __doc__ (as of 2008-08-02) for pygame.joystick.Joystick: # pygame.joystick.Joystick(id): return Joystick # create a new Joystick object # # Create a new joystick to access a ...
# It is safe to call this function more than once. self.fail()
################################################################################ if __name__ == '__main__': unittest.main()
martbhell/wasthereannhlgamelastnight
src/lib/google/api_core/datetime_helpers.py
Python
mit
8,995
0.000445
# Copyright 2017 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
Returns: (:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message """ i
nst = ( self if self.tzinfo is not None else self.replace(tzinfo=datetime.timezone.utc) ) delta = inst - _UTC_EPOCH seconds = int(delta.total_seconds()) nanos = self._nan
obi-two/Rebelion
data/scripts/templates/object/static/particle/shared_particle_test_71.py
Python
mit
445
0.047191
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): r
esult = Static() result.template = "object/static/particle/shared_particle_test_71.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### B
EGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
luisg123v/openacademy-project
openacademy/wizards/openacademy_wizard.py
Python
apache-2.0
633
0
# -*- coding:
utf-8 -*- from openerp import models, fields, api class Wizard(models.TransientModel): _name = 'openacademy.wizard' def _default_sessions(self): return self.env['openacademy.session'].browse( self._context.get('active_ids')) session_ids = fields.Many2many( 'openacademy
.session', string="Sessions", required=True, default=_default_sessions) attendee_ids = fields.Many2many('res.partner', string="Attendees") @api.multi def subscribe(self): for session in self.session_ids: session.attendee_ids |= self.attendee_ids return {}
mbi/django-simple-captcha
captcha/tests/views.py
Python
mit
3,752
0.000533
from captcha.fields import CaptchaField from django import forms from django.contrib.auth.models import User from django.http import HttpResponse try: from django.template import engines __is_18 = True except ImportError: from django.template import loader __is_18 = False TEST_TEMPLATE = r""" <!DOC...
class Meta: model = User fields = ("subject", "sender", "captcha") ret
urn _test(request, CaptchaTestModelForm) def test_custom_error_message(request): class CaptchaTestErrorMessageForm(forms.Form): captcha = CaptchaField( help_text="asdasd", error_messages=dict(invalid="TEST CUSTOM ERROR MESSAGE") ) return _test(request, CaptchaTestErrorMessageForm)...
adaptivelogic/django-cms
cms/test_utils/project/urls.py
Python
bsd-3-clause
1,114
0.008977
from cms.utils.conf import get_cms_setting from django.conf import settings from django.conf.urls.defaults import handler500, handler404, patterns, include, \ url from django.contrib import admin try: from django.conf.urls.i18n import i18n_patterns except
ImportError: from i18nurls.i18n import i18n_patterns from django.contrib.staticfiles.urls import staticfiles_urlpatterns admin.autodiscover() urlpatterns = patterns('', #(r'', include('django.contrib.staticfiles.urls')), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_roo...
settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^media/cms/(?P<path>.*)$', 'django.views.static.serve', {'document_root': get_cms_setting('MEDIA_ROOT'), 'show_indexes': True}), url(r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'), ) urlpatterns += staticfiles_urlpattern...
rolandgeider/wger
wger/manager/tests/test_ical.py
Python
agpl-3.0
7,598
0.002764
# This file is part of wger Workout Manager. # # wger Workout Manager 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 Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger W...
223344556677889900' response = self.client.get(reverse('manager:workout:ical', kwargs={'pk': 3, 'uidb64': uid, 'token': token})) self.assertEqual(resp
onse.status_code, 403) def export_ical(self, fail=False): """ Helper function """ response = self.client.get(reverse('manager:workout:ical', kwargs={'pk': 3})) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEq...
zeptonaut/catapult
dashboard/dashboard/post_data_handler.py
Python
bsd-3-clause
1,637
0.004276
# Copyright 2015 The Chro
mium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A helper request handler for request handlers that receive data.""" import logging from dashboard import request_handler from dashboard import utils class PostDataHandler(requ...
the IP of the request against the white list. Real sub-class handlers should override this and use _CheckIpAgainstWhitelist; this is provided here for convenience in tests. """ self._CheckIpAgainstWhitelist() def _CheckIpAgainstWhitelist(self): """Checks the remote address of the request against...
azumimuo/family-xbmc-addon
plugin.video.phstreams/resources/lib/resolvers/miplayer.py
Python
gpl-2.0
902
0.018847
# -*- coding: utf-8 -*- import re,urlparse,base64 from resources.lib.modules import client domains = ['miplayer.net'] def resolve(url): try: try: referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0] except: referer=url id = urlpar...
r.net/embedplayer.php?width=640&height=480&id=%s'%id result = client.request(url, referer=referer) curl = re.compile("curl\s*=\s*\"(.+?)\"").findall(result)[0] curl = base64.b64decode(curl) url = curl + ' swf
Url=http://otronivel.me/jw7/jwplayer.flash.swf flashver=WIN/2019,0,0,226 timeout=15 live=true swfVfy=1 pageUrl=http://miplayer.net/embedplayer.php?width=640&height=480&id=%s&autoplay=true&strech=exactfit'%id return url except: return
knaggsy2000/stormforce-mq
plugins/plugin_core_debug.py
Python
bsd-3-clause
4,779
0.019042
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # Copyright/License Notice (Modified BSD License) # ######################################################################### ###################################################...
# ################################################### from plugin_core_base import PluginBase ########### # Classes # ########### class Plugin(PluginBase): def __init__(self): PluginBase.__init__(self) self.MQ_ROUTING_KEY = "events.#" def getScriptP
ath(self): return self.os.path.realpath(__file__) def onEventReceived(self, basic_deliver, properties, body): PluginBase.onEventReceived(self, basic_deliver, properties, body) self.log.debug("Deliver: {0}".format(basic_deliver)) self.log.debug("Header: {0}".format(properties)) self.log.debug("Body: ...
omegachysis/biohex
biohex/life.py
Python
apache-2.0
28,573
0.005425
import random import glob from os import path import biohex import math import traceback # storage class for constants class locals(): class distanceLookup(): RING_CACHE = 0 BIT_LISTER = 1 try: # load up bit graphic asset names bitList = [] for file in glob.glob("biohex/bitGraphics/...
newLooper = Looper(newBit, looperCommand, pickledLooper[1]) newLooper.timer = pickledLooper[0] newLooper.paused = pickledLooper[3] pickledVector = newBit.vector newBit.vector = Vector(newBit, pickledVector[0]) newBit._ahead = pickledVector[1] class Bit(object): """ The basic un...
est" # stores a record of all bits, accessible to others. # stored on a 'name' basis. # ex.: {"Test" : [Bit, Bit, ...], "Test 2" : [...]} lister = {} # ENTHALPY acts as a simulated unit of energy. # Use a enthalpy looper to simulate a breakdown # without a constant source of energy. ...
khasm08/PythonSandbox
wsgi.py
Python
apache-2.0
4,161
0.010815
# This file contains the WSGI configuration required to serve up your # web application at http://khasm08.pythonanywhere.com/ # It works by setting the variable 'application' to a WSGI handler of some # description. # # +++++++++++ GENERAL DEBUGGING TIPS +++++++++++ # getting imports and sys.path right can be fiddly! ...
plication # # NB -- many Flask guides suggest you use a file called run.py; that's # not necessary on PythonA
nywhere. And you should make sure your code # does *not* invoke the flask development server with app.run(), as it # will prevent your wsgi file from working.
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py
Python
bsd-3-clause
2,252
0
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import sys from cryptography import utils from cryptography.exceptions i...
key_material, self._salt, self._length, self._n, self._r, self._p ) def verify(self, key_material, expected_key): derived_key = self.derive(key_material) if not constant_time.bytes_eq(derived_
key, expected_key): raise InvalidKey("Keys do not match.")
emjelde/rstats
RStatsHistory.py
Python
apache-2.0
3,662
0.004642
#!/usr/bin/python # Copyright (C) 2014 - Evan Mjelde # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
y == 0 else day) @staticmethod def to_unit(value, unit=None): if unit is not None: unit = unit.lower() if unit == 'k': return value / 1024 if unit == 'm': return value / (1024 * 1024) if unit == 'g':
return value / (1024 * 1024 * 1024) return value def _print_counters(self, counters, unit=None): for counter in counters: if counter.date != 0: print("{0} : Upload {1} : Download {2}".format( self.get_date(counter.date).strftime("%Y/%m/%d"), ...
fcitx/mozc
src/__init__.py
Python
bsd-3-clause
1,579
0
# -*- coding: utf-8 -*- # Copyright 2010-2021, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this...
GLIGEN
CE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __author__ = "mazda"
zikrach/euler
euler_2.py
Python
gpl-2.0
183
0.010929
# -
*- coding: utf-8 -*- """solve problem 2
""" n = 1 m = 1 result = 0 while n < 4000000: s = n + m n = m m = s if s % 2 == 0: result += s print result
litex-hub/litex-boards
litex_boards/platforms/sqrl_xcu1525.py
Python
bsd-2-clause
14,980
0.00494
# # This file is part of LiteX-Boards. # # Copyright (c) 2020 David Shah <dave@ds0.me> # Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import Pins, Subsignal, IOStandard, Misc from litex.build.xilinx import XilinxPlatform, Viva...
33"), IOStandard("DIFF_POD12"
), Misc("OUTPUT_IMPEDANCE=RDRV_40_40"), Misc("PRE_EMPHASIS=RDRV_240"), Misc("EQUALIZATION=EQ_LEVEL2")), Subsignal("dqs_p", Pins("BB35 AU29 BA30 BD28 AM31 BE38 AL28 AV33"), IOStandard("DIFF_POD12"), Misc("OUTPUT_IMPEDANCE=RDRV_40_40"), Misc(...
martinhbramwell/GData_OpenERP_Data_Pump
openerp_utils.py
Python
agpl-3.0
1,342
0
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2013-11-25 @author: Martin H. Bramwell ''' import oerplib import sys import socket from models.OErpModel import OErpModel class OpenERP(object): def __init__(self, credentials): db = credentials['db_na
me'] user_id = credentials['user_id'] host_name = credentials['host_name'] host_port = credentials['host_port'] user_pwd = credentials['user_pwd'] print "Getting connection to {} for {}".format(db, user_id) try: oerp = oerplib.OERP( server=hos...
nnection['super'] = oerp if db in oerp.db.list(): db_connect(user_id, user_pwd, db) else: print "There is no database called : {}".format(db) except socket.gaierror: sys.exit( "Is this the correct URL : {}".format(host_name)) ...
sevmardi/University-of-Applied-Sciences-Leiden
Python/ifscp_Opdrachten/Opdracht1.py
Python
mit
758
0.014512
__author__ = 'SM' import sys import # from tkinter import * # #create new window # root = Tk() # root.title("Hello world app") # root.geometry('200x85') # # app = Frame() # app.grid() # lbl = Label(app, text = "Hello World!") # lbl.grid() # # bttn1 = Button(app, text = "Press") # bttn1.grid() # # root.mainloop() ...
o) # The rest is known already... a.setMa
inWidget(hellobutton) hellobutton.show() a.exec_loop()
mardix/Paginator.py
paginator.py
Python
mit
4,801
0.001041
""" Paginator """ from math import ceil from six import string_types from six.moves import range class Paginator(object): PER_PAGE = 10 total_pages = 0 total_items = 0 callback = None def __init__(self, query, page=1, per_page=PER_PAGE, total=None, padding=0, callback=None, stati...
eft_current=3, right_current=4, right_edge=2): """ :param query: Iterable to paginate. Can be a query object, list or any iterables :param page: current page :param per_page: max number of items per page :param total: Max number of items. If not
provided, it will use the query to count :param padding: Number of elements of the next page to show :param callback: a function to callback on each item being iterated. :param static_query: bool - When True it will return the query as is, without slicing/limit. Usally when using the paginator ...
ariwaranosai/acfun-LDA
last.py
Python
gpl-2.0
765
0.014379
def topic_id2word(p): f = open(p + "/model.vPhi") wfile = open(p + "/model.vPhi.new", "w") words = load(p + "/dict.txt"); for line in f: dict = {} i = 0 for w in line.strip().split(" "): try: tmp = float(w) except: print w ...
n(path) i = 0 for line in
f: l = line.split() dict[i] = l[0] i+=1 return dict topic_id2word(".")
haphaeu/yoshimi
EulerProject/038.py
Python
lgpl-3.0
1,137
0.031662
def isPandigital(strN): Ln = [c for c in strN] Ln.sort() if Ln == ['1', '2', '3', '4', '5', '6', '7', '8', '9']: return True return False listPans=[] listMultiplier=[] #dont know if these limits are ok i=9 while i<9999: n=2 while n<999: j=1 strProd='' while j<n:...
int i, n, strProd if isPandigital(strProd): listPans.append(prod) listMultiplier.append(i) print "Pandigital", i, j, strProd n+=1 i+=1 #output: #Pandigital 9 6 918273645 #Pandigital 19
2 4 192384576 #Pandigital 219 4 219438657 #Pandigital 273 4 273546819 #Pandigital 327 4 327654981 #Pandigital 6729 3 672913458 #Pandigital 6792 3 679213584 #Pandigital 6927 3 692713854 #Pandigital 7269 3 726914538 #Pandigital 7293 3 729314586 #Pandigital 7329 3 732914658 #Pandigital 7692 3 769215384 #Pandigital 7923 3 ...
jaruba/chromium.src
build/android/pylib/remote/device/remote_device_environment.py
Python
bsd-3-clause
6,592
0.009709
# Copyright 2014 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. """Environment setup and teardown for remote devices.""" import logging import os import random import sys from pylib import constants from pylib.base impo...
ized.SanitizeLogging(self._verbose_count, logging.WARNING): dev_list_res = appurify_sanitized.api.devices_list(self._access_token) remote_device_helper.TestHttpResponse(dev_list_res,
'Unable to generate access token.') device_list = dev_list_res.json()['response'] random.shuffle(device_list) for device in device_list: if device['os_name'] != 'Android': continue if self._remote_device and device['name'] != self._remote_device: continue if (self._rem...
tsgit/invenio
modules/miscutil/lib/upgrades/invenio_2014_06_10_new_field_address.py
Python
gpl-2.0
2,257
0.00576
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) a...
tion, Inc., ## 59 Temple Pla
ce, Suite 330, Boston, MA 02111-1307, USA. from logging import warn from invenio.dbquery import run_sql depends_on = ['invenio_release_1_1_0'] def info(): return "New address field." def do_upgrade(): pass def do_upgrade_atlantis(): field_id = run_sql( """INSERT INTO field SET name='address'...
ryansb/bugwarrior
tests/test_github.py
Python
gpl-3.0
2,426
0
import datetime import pytz from bugwarrior.services.github import GithubService from .base import ServiceTest class TestGithubIssue(ServiceTest): maxDiff = None SERVICE_CONFIG = { 'github.login': 'arbitrary_login', 'github.password': 'arbitrary_password', 'github.username': 'arbitr...
self.assertEqual(issue._normalize_label_to_tag('needs work'), 'needs_work') def test_to_taskwarrior(self): self.service.import_labels_as_tags = True issue = self.service.get_issue_for_record( self.arbitrary_issue, self.arbitrary_extra ...
ault_priority, 'annotations': [], 'tags': ['bugfix'], issue.URL: self.arbitrary_issue['html_url'], issue.REPO: self.arbitrary_issue['repo'], issue.TYPE: self.arbitrary_extra['type'], issue.TITLE: self.arbitrary_issue['title'], issue.NUM...
ProvincalInovationManagement/provinceManagement
expert/migrations/0002_auto__del_field_project_project_type.py
Python
agpl-3.0
872
0.005734
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Project.project_type' db.delete_column('expert_project', 'project_type') def backwar...
roject': { 'Meta': {'object_name': 'Pr
oject'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'project_name': ('django.db.models.fields.TextField', [], {}) } } complete_apps = ['expert']
benallard/pythoncard
test/runtests.py
Python
lgpl-3.0
783
0.006386
import os, re, sys import unittest """ Greatly imspired from Dive into Python chap. 16.7 """ sys.path = [os.path.dirname(os.path.dirname(os.path.abspath(__file__)))] + sys.path def allTests(): path = os.path.abspath(os.path.dirname(__file__)) files = os.listdir(path) print(files) test = re.compile("^...
omModule return unittest.TestSuite(map(load,
modules)) if __name__ == "__main__": unittest.main(defaultTest="__main__.allTests", module=None)
NSLS-II-HXN/ipython_ophyd
startup/users_plans.py
Python
bsd-2-clause
119
0.008403
def m
yscan(n): for ii in range(n): yield from dmesh(dets1, zpssy, -0.5, 0.5, 40, zpssz, -0.5, 0.5, 40
, 3)
bigswitch/nova
nova/objects/keypair.py
Python
apache-2.0
8,795
0
# 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 by applicable law or agree...
nitial version # Version 1.1: String attributes updated to support unicode # Version 1.2: Added keypair type # Version 1.3: Name field is non-null # Version 1.4: Add localonly flag to get_by_name() VERSION = '1.4' fields = { 'id': fields.Integer
Field(), 'name': fields.StringField(nullable=False), 'user_id': fields.StringField(nullable=True), 'fingerprint': fields.StringField(nullable=True), 'public_key': fields.StringField(nullable=True), 'type': fields.StringField(nullable=False), } def obj_make_compatible...
bazelbuild/bazel-bench
utils/logger.py
Python
apache-2.0
1,409
0.006388
# Copyright 2019 The Bazel 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...
rn': '\033[33m%s\033[0m', # Yellow 'error': '\033[31m%s\033[0m', # Red } def _maybe_colorize
_text(text, color): """Colorize the text if running on a terminal.""" if not sys.stdout.isatty(): return text return _COLOR_TMPL[color] % text def log(text): """Logs a message using the logger singleton.""" logging.info(_maybe_colorize_text(text, 'info')) def log_warn(text): """Logs a warning messag...
mohikhsan/px-labeler
px-labeler/pxgui/ui_pxmarkerdialog.py
Python
mit
2,812
0.002845
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pxmarkerdialog.ui' # # Created by: PyQt5 UI code generator 5.8.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_PxMarkerDialog(object): def setupUi(self, PxMarkerDialog): ...
elf.pxmarker_table_widget.setRowCount(0) item = QtWidgets.QTableWidgetItem() self.pxmarker_table_widget.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.pxmarker_table_widget.setHorizontalHeaderItem(1, item) item = QtW
idgets.QTableWidgetItem() self.pxmarker_table_widget.setHorizontalHeaderItem(2, item) self.pxmarker_table_widget.horizontalHeader().setDefaultSectionSize(50) self.pxmarker_table_widget.horizontalHeader().setMinimumSectionSize(40) self.pxmarker_table_widget.horizontalHeader().setStretchLa...
jupyter-widgets/ipywidgets
python/ipywidgets/ipywidgets/widgets/tests/test_widget_image.py
Python
bsd-3-clause
4,422
0.000905
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. """Test Image widget""" import io import os from ipywidgets import Image import hashlib import pkgutil import tempfile from contextlib import contextmanager # Data @contextmanager def get_logo_png(): # Once t...
OGO_DATA = pkgutil.get_data('ipywidgets.widgets.tests', 'data/jupyter-logo-transparent.png') handle, fname = tempfile.mkstemp() os.close(handle) with open(fname, 'wb') as f: f.write(LOGO_DATA) yield fname os.remove(fname) LOGO_PNG_DIGEST = '3ff9eafd7197083...
f test_image_value(): random_bytes = b'\x0ee\xca\x80\xcd\x9ak#\x7f\x07\x03\xa7' Image(value=random_bytes) def test_image_format(): # Test that these format names don't throw an error Image(format='png') Image(format='jpeg') Image(format='url') def test_from_filename(): with get_logo_p...
petersn-github/Gandalf
stark-crawler/src/spiders/school.py
Python
apache-2.0
1,041
0.003058
# -*- coding: utf-8 -*- import scrapy class SchoolSpider(scrapy.Spider): name = "school" resources = "xhr" def start_requests(self):
#
中国教育在线 url = 'http://gkcx.eol.cn/soudaxue/queryschool.html?page=' # p=76 下载失败 p=88 下载失败 p=94 下载失败 下载完成 for num in range(1, 278): yield scrapy.Request(url=url + str(num), callback=self.parse) def parse(self, response): self.logger.info('正在选择页面元素 [%s]', response.url) ...
astrobin/astrobin
astrobin_apps_equipment/api/serializers/camera_edit_proposal_serializer.py
Python
agpl-3.0
1,081
0.00185
from rest_framework.exceptions import ValidationError from astrobin_apps_equipment.api.serializers.equipment_item_edit_proposal_serializer import \ EquipmentItemEditProposalSerializer from astrobin_apps_equipment.models import CameraEditProposal, Camera class CameraEditProposalSerializer(EquipmentItemEditProposa...
t_original_properties(self, target: Camera): return { 'type': target.type, 'sensor': target.sensor.pk if target.sensor else None, 'cooled': target.cooled, 'max_cooling': target.max_cooling, 'back_focus': target.back_focus, } def create(se...
fied: raise ValidationError('Modified cameras do not support edit proposals. Edit the regular variant instead.') return super().create(validated_data) class Meta(EquipmentItemEditProposalSerializer.Meta): model = CameraEditProposal fields = '__all__' abstract = False
salas106/irc-ltl-framework
utils/config.py
Python
mit
2,675
0.002617
# -*- coding: utf8 -*- """ The ``config`` module ===================== Create a named logger and return it so users can log in different log files : one for each module. """ __author__ = 'Salas' __copyright__ = 'Copyright 2014 LTL' __credits__ = ['Salas'] __license__ = 'MIT' __version__ = '0.2.0' __main...
_dir_path = path.abspath(path.join(os.sep, path.dirname(__file__), path.pardir, 'config')) config_file_path = path.join(config_dir_path, '{}.config.yaml'.format(config_prefix)) config_example_path = path.join(config_dir_path, '{}.exa
mple.yaml'.format(config_prefix)) try: with open(config_file_path, 'rb') as config_stream: config_dict = yaml.load(config_stream, Loader=Loader) except IOError: logger.info('') try: os.makedirs(config_dir_path) except OSErro...
rokurosatp/slackbotpry
slackbotpry/event.py
Python
mit
578
0
class Event: def __init__(self, bot, data): self.bot = bot self.data = data def post_message(self,
text): channel = self.data['channel'] return self.bot.post_message(text, channel) def add_reaction(self, emoji): channel = self.data['channel'] timestamp = self.data['ts'] return self.bot.add_reaction(emoj
i, channel, timestamp) def remove_reaction(self, emoji): channel = self.data['channel'] timestamp = self.data['ts'] return self.bot.remove_reaction(emoji, channel, timestamp)
koduj-z-klasa/pong
zadania/pong_z6.py
Python
mit
5,689
0.001423
# coding=utf-8 import pygame import pygame.locals class Board(object): """ Plansza do gry. Odpowiada za rysowanie okna gry. """ def __init__(self, width, height): """ Konstruktor planszy do gry. Przygotowuje okienko gry. :param width: :param height: ...
self.bounce_x() if self.rect.y < 0 or self.rect.y > board.surface.get_height(): self.bounce_y() for racket in args: if self.rect.colliderect(racket.rect): self.bounce_y() class Racket(Drawable): """ Rakietka, porusza się w osi X z ogr...
self.max_speed = max_speed self.surface.fill(color) def move(self, x): """ Przesuwa rakietkę w wyznaczone miejsce. """ delta = x - self.rect.x if abs(delta) > self.max_speed: delta = self.max_speed if delta > 0 else -self.max_speed self...
superdesk/superdesk-aap
server/aap/publish/formatters/anpa_formatter.py
Python
agpl-3.0
8,923
0.00381
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from copy imp...
ID_FIELD)) pub_seq_num = superdesk.get_resource_service('subscribers').generate_sequence_number(subscriber) anpa = [] if codes:
anpa.append(b'\x05') anpa.append(' '.join(codes).encode('ascii')) anpa.append(b'\x0D\x0A') # start of message header (syn syn soh) anpa.append(b'\x16\x16\x01') anpa.append(get_service_level(category, formatted_article).enco...
eddiedb6/ej
web/metadata/EJUIMapPage.py
Python
mit
493
0.002028
{ "uidPageMap": { W3Const.w3PropType: W3Const.w3TypePanel, W3Const.w3PropSubUI: [ "uidMSMap" ] }, # Map "uidMSMap": { W3Const.w3PropType: W3Const.w3TypeMap, W3Cons
t.w3PropMap: { W3Const.w3AttrMapLocation: "", W3Const.w3AttrMapKey: "" }, W3Const.w3PropCSS: { "border": "2px solid", "min-w
idth": "800px", "min-height": "600px" } } }
adrn/gary
gala/integrate/setup_package.py
Python
mit
1,236
0
from distutils.core import Extension from collections import defaultdict def get_extensions(): import numpy as np exts = [] # malloc mac_incl_path = "/usr/include/malloc" cfg = defaultdict(list) cfg['include_dirs'].append(np.get_include()) cfg['include_dirs'].append(mac_incl_path) c...
s'].append('gala/integrate/cyintegrators/dop853.pyx') cfg['sources'].append('gala/integrate/cyintegrators/dopri/dop853.c')
exts.append(Extension('gala.integrate.cyintegrators.dop853', **cfg)) return exts
npuichigo/ttsflow
third_party/tensorflow/tensorflow/python/kernel_tests/base64_ops_test.py
Python
apache-2.0
5,658
0.009721
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
, msg, pad): with self.test_session() as sess: if pad: encoded, decoded = sess.run([self._encoded_t, self._decoded_t], feed_dict={self._msg: msg}) else: encoded, decoded = sess.run([self._enc
oded_f, self._decoded_f], feed_dict={self._msg: msg}) if not isinstance(msg, (list, tuple)): msg = [msg] encoded = [encoded] decoded = [decoded] base64_msg = [base64.urlsafe_b64encode(m) for m in msg] if not pad: base64_msg = [self._RemovePad(m, ...
food52/thumbor
thumbor/filters/strip_icc.py
Python
mit
413
0
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/globocom/
thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com from thumbor.
filters import BaseFilter, filter_method class Filter(BaseFilter): @filter_method() def strip_icc(self): self.engine.strip_icc()
ebolyen/qiime2
qiime2/plugin/tests/test_plugin.py
Python
bsd-3-clause
4,900
0
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2017, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
ions["i-shouldn't-do-this"] = "my-action" with self.assertRaises(TypeError): actions["merge_mappings"] = "my-action" def test_methods(self): methods = self.plugin.methods self.assertEqual(methods.keys(), {'merge_
mappings', 'concatenate_ints', 'split_ints', 'identity_with_metadata', 'identity_with_metadata_category', 'identity_with_optional_metadata', 'identity_with_optional_metadata_category', 'para...