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
bne/hortee
hortee/production.py
Python
apache-2.0
31
0
from hortee.setti
ngs import *
bgroff/kala-app
django_kala/organizations/views/new_organization.py
Python
mit
1,353
0.002217
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.shortcuts import redirect from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.translation import ugettext as _ ...
): ret
urn { 'form': self.form, } @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): if not request.user.is_superuser: raise PermissionDenied(_('You do not have permission to create a new organization.')) self.form = DetailsForm(request.POST...
stormi/tsunami
src/primaires/interpreteur/masque/noeuds/base_noeud.py
Python
bsd-3-clause
2,736
0.000368
# -*-coding:Utf-8 -* # Copyright (c) 2010 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # 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...
ULAR 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 NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) ...
theonlydude/RandomMetroidSolver
web/backend/plando.py
Python
mit
2,305
0.003471
from web.backend.utils import loadPresetsList, transition2isolver, getAddressesToRead from graph.graph_utils import vanillaTransitions, vanillaBossesTransitions, vanillaEscapeTransitions, GraphUtils from logic.logic import Logic from utils.version import displayedVersion from gluon.html import OPTGROUP class Plando
(object): def __init__(self, session, request, cache): self.session = session self.request = request self.cache = cache # required for GraphUtils access to access points Logic.factory('vanilla') def run(self): # init session if self.session.plando is None...
te": {}, "preset": "regular", "seed": None, "startLocation": "Landing Site", # rando params "rando": {}, # set to False in plando.html "firstTime": True } # load presets list (s...
ayan-usgs/sci-wms
sciwms/__init__.py
Python
gpl-3.0
76
0
import logging logg
er = logging.get
Logger('sci-wms') __version__ = '1.0.0'
MrYsLab/rb4s
redbot_accel.py
Python
gpl-3.0
18,018
0.003219
#!/usr/bin/env python3 """ Copyright (c) 2015 Alan Yorinks All rights reserved. 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 versio...
self.data_val, Constants.CB_TYPE_ASYNCIO) ctrl1 = await self.wait_for_read_result() ctrl1 = (ctrl1[self.data_start]) & ~0x01 self.callbac
k_data = [] await self.board.i2c_write_request(self.address, [register, ctrl1]) async def set_scale(self, scale): """ Set the device scale register. Device must be in standby before calling this function @param scale: scale factor @return: No return value ""...
danhuynhdev/taskbuster
taskbuster/urls.py
Python
mit
1,187
0
"""taskburster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Clas...
h.urls')), ] urlpatterns += i18n_pattern
s( url(r'^$', home, name='home'), url(r'^admin/', include(admin.site.urls)), )
maciekswat/dolfin_1.3.0
test/documentation/test.py
Python
gpl-3.0
1,132
0
# Copyright (C) 2011 Marie E. Rognes # # This file is part of DOLFIN. # # DOLFIN is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version....
s = ["verify_demo_code_snippets.py"] failed = [] for test in tests: command = "%s %s" % (sys.executable, test) fail, output = get_status_outp
ut(command) if fail: failed.append(fail) print "*** %s failed" % test print output else: print "OK" sys.exit(len(failed))
the-zebulan/CodeWars
tests/kyu_6_tests/test_compare_versions.py
Python
mit
729
0
import unittest from katas.kyu_6.compa
re_versions import compare_versions class C
ompareVersionsTestCase(unittest.TestCase): def test_true(self): self.assertTrue(compare_versions('11', '10')) def test_true_2(self): self.assertTrue(compare_versions('11', '11')) def test_true_3(self): self.assertTrue(compare_versions('10.4.6', '10.4')) def test_false(self): ...
nesdis/djongo
tests/django_tests/tests/v21/tests/db_functions/test_pad.py
Python
agpl-3.0
1,830
0.00165
from django.db.models import CharField, Value from django.db.models.functions import Length, LPad, RPad from django.test import TestCase from .models import Author class PadTests(TestCase): def test_pad(self): Author.objects.create(name='John', alias='j') tests = ( (LPad('name', 7, Va...
(RPad('name', 7, Value('xy')), 'Johnxyx'), (LPad('name', 6, Value('x')), 'xxJohn'), (RPad('name', 6, Value('x')), 'Johnxx'), # The default pad string is a space. (LPad('name', 6), ' John'), (RPad('name', 6),
'John '), # If string is longer than length it is truncated. (LPad('name', 2), 'Jo'), (RPad('name', 2), 'Jo'), (LPad('name', 0), ''), (RPad('name', 0), ''), ) for function, padded_name in tests: with self.subTest(function=function...
happz/ducky
ducky/mm/__init__.py
Python
mit
24,453
0.010714
from six import iteritems, itervalues from six.moves import range from ..interfaces import ISnapshotable from ..errors import AccessViolationError, InvalidResourceError from ..util import align, sizeof_fmt, Flags from ..snapshot import SnapshotNode import enum DEFAULT_MEMORY_SIZE = 0x1000000 # Types from ctypes imp...
cess memory on this address: page={}, offset={}'.format(self.index, offset)) def read_u16(self, offset): """ Read word. This operation is implemented by child classes. :param
int offset: offset of requested word. :rtype: int """ raise NotImplementedError('Not allowed to access memory on this address: page={}, offset={}'.format(self.index, offset)) def read_u32(self, offset): """ Read longword. This operation is implemented by child classes. :param int offse...
credativ/gofer
src/gofer/agent/manager.py
Python
lgpl-2.1
5,843
0
# # Copyright (c) 2015 Red Hat, Inc. # # This software is licensed to you under the GNU Lesser General Public # License as published by the Free Software Foundation; either version # 2 of the License (LGPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # includin...
def run(self): """ The thread main. """ try: socket = self.listen()
self.accept(socket) except Exception: log.exception(self.host) def dispatch(self, call): """ Dispatch the call to the handler. :param call: A *call* document. :type call: Document """ reply = Document() try: method = ge...
navijo/FlOYBD
Django/mysite/floybd/urls.py
Python
mit
10,036
0.005281
import os from django.conf.urls import url from . import views from .earthquakes import viewsEarthquakes from .weather import viewsWeather from .gtfs import viewsGTFS from django.http import HttpResponseRedirect from .utils.utils import * from django.db import connection import simplekml import time import subprocess ...
, url('clearKML', views.clearKML, name='clearKML'), url('weatherStats', viewsWeather.weatherStats, name='weatherStats'), url('dayWeather', viewsWeather.weatherConcreteIndex, name='dayWeather'), url('predictWeatherStats',
viewsWeather.weatherPredictionsStats, name='predictWeatherStats'), url('predictWeather', viewsWeather.weatherPredictions, name='predictWeather'), url('weatherDemos', views.weatherDemos, name='weatherDemos'), url('weather', views.weatherIndex, name='weather'), url('currentWeather', viewsWeather.currentW...
ajurcevic/calibre-web
cps/epub.py
Python
gpl-3.0
4,225
0.003314
#!/usr/bin/env python # -*- coding: utf-8 -*- import zipfile from lxml import etree import os import uploader from iso639 import languages as isoLanguages def extractCover(zipFile, coverFile, coverpath, tmp_file_name): if coverFile is None: return None else: zipCoverPath = os.path.join(coverp...
section[0], coverpath, tmp_file_path) else: meta_cover = tree.xpath("/pkg:package/pkg:metadata/pkg:meta[@name='cover']/@content", namespaces=ns) if len(meta_cover) > 0: coversection = tree.xpath("/pkg:package/pkg:manifest/pkg:item[@id='"+meta_cover[0]+"']/@href", namespaces=ns) ...
if filetype == "xhtml" or filetype == "html": #if cover is (x)html format markup = epubZip.read(os.path.join(coverpath, coversection[0])) markupTree = etree.fromstring(markup) # no matter xhtml or html with no namespace imgsrc = ...
kadubarbosa/hydra1
miles2_table.py
Python
gpl-2.0
1,347
0.019302
# -*- coding: utf-8 -*- """ Created on 26/11/15 @author: Carlos Eduardo Barbosa Convert table with SSP parameters of MILES II from the original to the appropriate format for the MCMC run. """ import os import numpy as np from config import * if __name__ == "__main__": os.chdir(os.path.join(home, "tables")) ...
es2, dtype=str) header = data[0] names = data[:,0] cols = np.array([2,3,4,5,6,7,8,9,14,15,16,17,18,24,25,26,27,28,29,30,31, 32,33,34,35]) data = data[:,cols] # lick = np.loadtxt("BANDS", dtype=str, usecols=(0,))
# for a in zip(header[cols], lick): # print a table = [] for name, d in zip(names, data): Z = name[8:13].replace("m", "-").replace("p", "+") age = name[14:21] alpha = name[25:29] scale = name[30:] if scale not in ["Ep0.00", "Ep0.40"]: continue ...
affan2/django-alphabetfilter
alphafilter/admin.py
Python
apache-2.0
788
0.003807
""" This file unregisters the admin class for each model specified in ALPHAFILTER_ADMIN_FIELDS and replaces it with a new admin class that subclasses both the original admin and one with an alphabet_filter attribute """ from django.db.models import get_model from django.contrib import admin from django.conf import s...
s MODEL_REGISTRY = getattr(settings, 'ALPHAFILTER_ADMIN_FIELDS', {}) FIELDS = {} for key, val in MODEL_REGISTRY.items(): if isinstance(key, basestring): FIELDS[get_model(*key.split('.'))] = val for model, modeladmin in admin.site._registry.items()
: if model in FIELDS: admin.site.unregister(model) admin.site.register(model, type('newadmin', (modeladmin.__class__,), { 'alphabet_filter': FIELDS[model], }))
ycool/apollo
cyber/python/cyber_py/cyber.py
Python
apache-2.0
10,449
0.000383
# **************************************************************************** # Copyright 2018 The Apollo 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 # # ht...
shutdown() def waitforshutdown(): """ waitforshutdown. """ return _CYBER_INIT.py_waitforshutdown() # //////////////////////////////class////////////////////////////// class Writer(object): """ Class for cyber writer wrapper. """ def __init__(self, name, writer, data_type): ...
""" return _CYBER_NODE.PyWriter_write(self.writer, data.SerializeToString()) class Reader(object): """ Class for cyber reader wrapper. """ def __init__(self, name, reader, data_type): self.name = name self.reader = reader self.data_type = data_type class Client(o...
EmanueleCannizzaro/scons
test/Fortran/F03FILESUFFIXES.py
Python
mit
4,014
0.001495
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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 us...
e = open(args[0], 'rb') outfile = open(out, 'wb') for l in infile.readlines(): if l[:len(comment)] != comment: outfile.write(l) sys.exit(0) """) # Test default file suffix: .f90/.F90 for F90 test.write('SConstruct', """ env = Environment(LINK = r'%(_python_)s mylink.py', LINKFL
AGS = [], F03 = r'%(_python_)s myfortran.py f03', FORTRAN = r'%(_python_)s myfortran.py fortran') env.Program(target = 'test01', source = 'test01.f') env.Program(target = 'test02', source = 'test02.F') env.Program(target = 'test03', source = 'test03.for') env.Program(target = 'test04...
eek6/squeakspace
admin/init_server_db.py
Python
gpl-3.0
325
0
#!/usr/bin/python2.7 # Run this script as user: www-data import os import server_path import squeakspace.server.db_sqlite3 as db import config try: os.remove(config.db_path) except OSError: pass conn = db.connect(config.db_path) c = db
.cursor(conn) db.make
_db(c, config.total_quota) db.commit(conn) db.close(conn)
antljones/saw
saw/views/url.py
Python
mit
940
0.014894
from pyramid.view import view_config @view_config(route_name='url#index', request_method='GET', renderer='templates/url/index.pt') def index(request): return {} @view_config(route_name='url#show', request_method='GET', renderer='templates/url/show.pt') def show(request): return {} @view_config(route_name='ur...
ates/url/create.pt') def create(request): return {} @view_config(route_name='url#edit', request_method='GET', renderer='templates/url/edit.pt') def edit(request): return {} @view_config(route_name='url#update', request_method='GET', renderer='templates/url/update.pt') def update(request): return {} @view...
name='url#destroy', request_method='GET', renderer='templates/url/destroy.pt') def destroy(request): return {}
thijstriemstra/acidswf
python/acidswf/application/amf.py
Python
gpl-3.0
1,733
0.004616
# Copyright (c) The AcidSWF Project. # See LICENSE.txt for details. """ Support for creating a service which runs a web server. @since: 1.0 """ import logging from twisted.python import usage from twisted.application import service from acidswf.service import createAMFService optParameters = [ ['log-level', ...
cating that this is not possible. If no server port was supplied, select a default appropriate for the other opti
ons supplied. """ pass #if self['https']: # try: # from twisted.internet.ssl import DefaultOpenSSLContextFactory # except ImportError: # raise usage.UsageError("SSL support not installed") def makeService(options): top_service = service.M...
huangkuan/hack
lib/gcloud/monitoring/client.py
Python
apache-2.0
7,310
0
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
cumentation: https://cloud.google.com/monitoring/api/v3/filters """ return MetricDescriptor._list(self, filter_string) def fetch_resource_descriptor(self, resource_type): """Look up a resource descriptor by type. Example:: >>> print(client.fetch_resource_de...
urce_type: The resource type name. :rtype: :class:`~gcloud.monitoring.resource.ResourceDescriptor` :returns: The resource descriptor instance. :raises: :class:`gcloud.exceptions.NotFound` if the resource descriptor is not found. """ return ResourceDescriptor._fetch(...
endlessm/chromium-browser
third_party/llvm/lldb/test/API/lang/c/anonymous/TestAnonymous.py
Python
bsd-3-clause
6,073
0.000988
"""Test that anonymous structs/unions are transparent to member access""" import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class AnonymousTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf( compiler="ic...
ions=1, loc_exact=True) # Now launch the process, and do not stop at entry point. process = target.LaunchSi
mple( None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, substrs=['stopped', 'stop r...
buildbot/supybot
test/test_ircmsgs.py
Python
bsd-3-clause
10,535
0.001804
### # Copyright (c) 2002-2005, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, ar
e permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following discl
aimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to...
sid88in/incubator-airflow
airflow/contrib/operators/gcp_compute_operator.py
Python
apache-2.0
7,129
0.001964
# -*- coding: utf-8 -*- # # 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 #...
'google_cloud_default', api_version='v1', *args, **kwargs): super(GceInstanceStopOperator, self).__init__( project_id=project_id, zone=zone, resource_id=resource_id, gcp_conn_id=gcp_conn_id, api_version=api_version, *args, **kwargs) def execute(self...
chineType", regexp="^.+$"), ] class GceSetMachineTypeOperator(GceBaseOperator): """ Changes the machine type for a stopped instance to the machine type specified in the request. :param project_id: Google Cloud Platform project where the Compute Engine instance exists. :type project_id: st...
anryko/ansible
lib/ansible/modules/cloud/amazon/rds_snapshot_info.py
Python
gpl-3.0
12,831
0.002416
#!/usr/bin/python # Copyright (c) 2014-2017 Ansible Project # Copyright (c) 2017, 2018 Will Thames # Copyright (c) 2017, 2018 Michael De La Rue # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = t...
contains: {} vpc_id: description: ID of VPC containing the DB returned: always type: str
sample: vpc-abcd1234 cluster_snapshots: description: List of cluster snapshots returned: always type: complex contains: allocated_storage: description: How many gigabytes of storage are allocated returned: always type: int sample: 1 availability_zones: description: The av...
skaasj/dl4mt-material
session2/nmt.py
Python
bsd-3-clause
39,416
0.007687
''' Build a simple neural machine translation model ''' import theano import theano.tensor as tensor from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams import cPickle as pkl import numpy import copy import os import warnings import sys import time from scipy import optimize, stats from collections...
mplementation, the gradient is implemented on the GPU. Backpropagating through `theano.tensor.concatenate` yields slowdowns because the inverse operation (splitting) needs to be done on the CPU. This implementation does not have that problem. :usage: >>> x, y = theano.tensor.matrices('x', 'y') ...
the tensors will be joined along this axis. :returns: - out : tensor the concatenated tensor expression. """ concat_size = sum(tt.shape[axis] for tt in tensor_list) output_shape = () for k in range(axis): output_shape += (tensor_list[0].shape[k],) output_sha...
oznurf/EKSI_HIKAYE
hikaye/migrations/0002_auto_20150819_1605.py
Python
mit
342
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models,
migrations class Migration(migrations.Migration): dependencies = [ ('hikaye', '00
01_initial'), ] operations = [ migrations.RenameModel( old_name='stories', new_name='Story', ), ]
frmdstryr/enamlx
enamlx/widgets/plot_area.py
Python
mit
6,354
0.000158
# -*- coding: utf-8 -*- """ Copyright (c) 2015, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file COPYING.txt, distributed with this software. Created on Jun 11, 2015 """ import sys from atom.atom import set_default from atom.api import ( Callable, Int, Tuple, ...
# (int, hues) see intColor() # “RGB” hexadecimal strings; may begin with ‘#’ # “RGBA” # “RRGGBB”
# “RRGGBBAA” #: Brush fill type fill_brush = d_(Instance(BRUSH_ARGTYPES)) #: Symbol to use for points symbol = d_(Enum(None, "o", "s", "t", "d", "+")) #: Symbol sizes for points symbol_size = d_(Float(10, strict=False)) #: Symbol pen to use symbol_pen = d_(Instance(PEN_ARGTYPES))...
onehao/opensource
pyml/crawler/minispider/test/SpiderHtmlParserTest.py
Python
apache-2.0
3,201
0.010016
# -*- coding:utf-8 -*- ################################################################################ # # Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved # ################################################################################ ''' Created on 2015年3月14日 @author: Administrator ''' import ...
''' test the logic of parse_url ''' urls = self.parser.parse_url('http://pycm.baidu.com:8081/2/index.html', './urls', '.*\.(gif|png|jpg|bmp|html)$', 1, 1) #http://pycm.baidu.com:8081/page2_1.html', 'h
ttp://pycm.baidu.com:8081/2/3/index.html' self.assertIn("http://pycm.baidu.com:8081/page2_1.html", urls) self.assertIn("http://pycm.baidu.com:8081/2/3/index.html", urls) self.assertTrue(os.path.exists(self.path[0:-23] + 'urls' + os.sep + 'http%3A__pyc...
janhui/test_engine
dev/plugins/define_boundary_ids/shapefile.py
Python
lgpl-2.1
38,004
0.005289
""" hapefile.py Provides read and write support for ESRI Shapefiles. author: jlawhead<at>geospatialpython.com date: 20110927 version: 1.1.4 Compatible with Python versions 2.4-3.x """ from struct import pack, unpack, calcsize, error import os import sys import time import array # # Constants for shape types NULL = 0 P...
se
lf.dbf and len(self.fields) == 0: self.load() return f def __restrictIndex(self, i): """Provides list-like handling of a record index with a clearer error message if the index is out of bounds.""" if self.numRecords: rmax = self.numRecords - 1 if ...
lmprice/ansible
lib/ansible/modules/network/aci/aci_access_port_to_interface_policy_leaf_profile.py
Python
gpl-3.0
11,226
0.002494
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Bruno Calogero <brunocalogero@hotmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__
= type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: aci_access_port_to_interface_policy_leaf_profile short_description: Manage Fabric interface policy leaf profile interface selectors (infra:...
rtBlk) description: - Manage Fabric interface policy leaf profile interface selectors on Cisco ACI fabrics. notes: - More information about the internal APIC classes B(infra:HPortS), B(infra:RsAccBaseGrp) and B(infra:PortBlk) from L(the APIC Management Information Model reference,https://developer.cisco.com/docs/apic...
jahuth/convis
docs/filters-1.py
Python
gpl-3.0
218
0.009174
import convis import numpy as np import matplotlib.pylab as plt plt.figure() plt.imshow(convis.numerical_filters.gauss_filter_2d(4.0,4.0)) plt.figure() plt.plot(c
onvis.numerical_filters.expon
ential_filter_1d(tau=0.01))
SciGaP/DEPRECATED-Cipres-Airavata-POC
saminda/cipres-airavata/sdk/scripts/remote_resource/trestles/submit_v2.py
Python
apache-2.0
5,478
0.011135
#!/usr/bin/env python import lib_v2 as lib import sys import os def main(argv=None): """ Usage is: submit.py [--account <chargecode>] [--url <url>] -- <commandline> Run from the working dir of the job which must contain (in addition to the job files) a file named scheduler.conf with scheduler prop...
plete" cp -r * %s.complete echo "mv %s %s.sleep" mv %s %s.sleep echo "mv %s.complete %s" mv %s.complete %s echo "rm -rf %s.sleep" rm -rf %s.sleep echo "Finished copying working directory." """ % (lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, ...
e.write("curl %s\&status=DONE\n" % url) rfile.close() return lib.submitJob() return 0 if __name__ == "__main__": sys.exit(main())
appleseedhq/gaffer
python/GafferUI/__init__.py
Python
bsd-3-clause
12,297
0.024152
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2011-2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted prov...
ding to : # # http://qt-project.org/wiki/Differences_Between_PySide_and_PyQt if "PyQt" in __qtModuleName : QtCore = __import__( __qtModuleName + ".QtCore" ).QtCore QtCore.Signal = QtCore.pyqtSignal # import the submodule from those bindings and return it if lazy : import Gaffer return Gaffer.lazy...
port__( __qtModuleName + "." + name ) return getattr( qtModule, name ) ########################################################################## # Function to return the C++ address of a wrapped Qt object. This can # be useful if needing to implement part of the UI in C++ and the rest # in Python. #################...
theflofly/tensorflow
tensorflow/python/ops/rnn.py
Python
apache-2.0
66,326
0.004568
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
`Te
nsor` scalar. sequence_length: int32 `Tensor` vector of size [batch_size]. min_sequence_length: int32 `Tensor` scalar, min of sequence_length. max_sequence_length: int32 `Tensor` scalar, max of sequence_length. zero_output: `Tensor` vector of shape [output_size]. state: Either a single `Tensor` matr...
Modeful/poc
modeful/ui/diagram/relationship/composition.py
Python
gpl-3.0
774
0.003876
from kivy.graphics import Color, Line, Quad from modeful.ui.diagram.relationship import Trigonometry from modeful.ui.diagram.relationship.association import Association class Composition(Association): def __init__(sel
f, *args, **kwargs): super().__init__(*args, **kwargs) with self.canvas.before: Colo
r(0, 0, 0) self._diamond_bg = Quad(points=[0]*8) Color(0, 0, 0, .5) self._diamond_line = Line(points=[], width=1, close=True) def redraw(self, x1, y1, x2, y2): super().redraw(x1, y1, x2, y2) points = Trigonometry.get_diamond_points(x1, y1, ...
andrefbsantos/Tuxemon
tuxemon/core/components/ui/__init__.py
Python
gpl-3.0
8,220
0.001825
#!/usr/bin/python # -*- coding: utf-8 -*- # # Tuxemon # Copyright (C) 2014, William Edwards <shadowapex@gmail.com>, # Benjamin Bean <superman2k5@gmail.com> # # This file is part of Tuxemon. # # Tuxemon is free software: you can redistribute it and/or modify # it under the terms of the GNU General Pu...
self.original_height = surface.get_height() if scale: surfa
ce = self.scale_surface(surface) else: self.original_width = surface.get_width() self.original_height = surface.get_height() if scale: surface = self.scale_surface(surface) else: ...
ychab/mymoney
mymoney/apps/bankaccounts/models.py
Python
bsd-3-clause
2,268
0
from django.conf import settings from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from mymoney.core.utils.currencies import get_currencies class BankAccountManager(models.Manager): def get_user_bankaccounts(self, user): if not hasattr(...
e both just in case. if self.pk is None: self.balance += self.balance_initial # Otherwise update it with the new delta. else: original = BankAccount.objects.get(pk=self.pk)
self.balance += self.balance_initial - original.balance_initial super(BankAccount, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('banktransactions:list', kwargs={ 'bankaccount_pk': self.pk, })
ngokevin/cyder
cyder/cydns/cname/views.py
Python
bsd-3-clause
808
0
from cyder.cydns.views import CydnsDeleteView from cyder.cydns.views import CydnsDetailView from cyder.cydns.views import CydnsCreateView from cyder.cydns.views import CydnsUpdateView from cyder.cydns.views import CydnsListView from cyder.cydns.cname.models import CNAME from cyder.cydns.cname.forms import
CNAMEForm class CNAMEView(object): model = CNAME form_class = CNAMEForm queryset = CNAME.objects.all().order_by('fqdn') class CNAMEDeleteView(CNAMEView, CydnsDeleteView): """ """ class CNAMEDetailView(CNAMEView, CydnsDetailView): """ """ templat
e_name = "cname/cname_detail.html" class CNAMECreateView(CNAMEView, CydnsCreateView): """ """ class CNAMEUpdateView(CNAMEView, CydnsUpdateView): """ """ class CNAMEListView(CNAMEView, CydnsListView): """ """
appleseedhq/gaffer
python/GafferCortexUI/CompoundPlugValueWidget.py
Python
bsd-3-clause
11,940
0.039698
########################################################################## # # Copyright (c) 2012, John Haddon. All rights reserved. # Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided ...
rns the Collapsible widget used to contain the child widgets, # or None if this ui is not collapsible. def _collapsible( self ) : return self.__collapsible ## May be overridden by derived classes to specify which child plugs # are represented and in what order. def _childPlugs( self ) : return self.getPlug(...
plugName->widget makes us vulnerable to name changes. # See similar comments in StandardNodeUI and StandardNodeToolbar. def __updateCh
agustin380/scratchbling
src/products/api/serializers.py
Python
gpl-3.0
247
0
from rest_framework.serializers impo
rt ModelSe
rializer from ..models import BackScratcher class ProductsSerializer(ModelSerializer): class Meta: model = BackScratcher fields = ['id', 'name', 'description', 'price', 'sizes']
amwelch/a10sdk-python
a10sdk/core/interface/interface_loopback_ip.py
Python
apache-2.0
2,191
0.008672
from a10sdk.common.A10BaseClass import A10BaseClass class AddressList(A10BaseClass): """This class does not support CRUD Operations please use parent. :param ipv4_address: {"type": "string", "description": "IP address", "format": "ipv4-address"} :param ipv4_netmask: {"type": "string", "description":...
efer to `common/device_proxy.py`
URL for this object:: `https://<Hostname|Ip address>//axapi/v3/interface/loopback/{ifnum}/ip`. """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.required=[] self.b_key = "ip" self.a10_url="/axapi/v3/interface/loopback/{ifnum}/ip" self....
fevxie/odoo-saas-tools
saas_server/models/__init__.py
Python
lgpl-3.0
37
0
imp
ort sa
as_server import res_config
ipmb/PyMetrics
PyMetrics/halstead.py
Python
gpl-2.0
10,366
0.016593
""" Compute HalsteadMetric Metrics. HalsteadMetric metrics, created by Maurice H. HalsteadMetric in 1977, consist of a number of measures, including: Program length (N): N = N1 + N2 Program vocabulary (n): n = n1 + n2 Volume (V): V = N * LOG2(n) Difficulty (D): D = (n1/2) * (N2/n2) Effort (E...
self.numOperands += 1 sDict = self
.context.__repr__() k = (sDict,tok.text) self.uniqueOperands['token'][k] = self.uniqueOperands['token'].get(tok.text, 0) + 1 def processStmt( self, currentFcn, currentClass, stmt, *args, **kwds ): """ Collect statement data for Halstead metrics.""" result = None ...
ideascube/ideascube
ideascube/library/migrations/0006_auto_20160728_1317.py
Python
agpl-3.0
3,408
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-07-28 13:17 from __future__ import unicode_literals from django.db import migrations import ideascube.models class Migration(migrations.Migration): dependencies = [ ('library', '0005_auto_20160712_1324'), ] operations = [ migra...
ol de colombia'), ('es-mx', 'Español de mexico'), ('es-ni', 'Español de nicaragua'), ('es-ve', 'Español de venezuela'), ('et', 'Eesti'), ('eu', 'Basque'), ('fa', 'فارسی'), ('fi', 'Suomi'), ('fr', 'Français'), ('fy', 'Frysk'), ('ga', 'Gaeilg...
indi'), ('hr', 'Hrvatski'), ('hu', 'Magyar'), ('ia', 'Interlingua'), ('id', 'Bahasa indonesia'), ('io', 'Ido'), ('is', 'Íslenska'), ('it', 'Italiano'), ('ja', '日本語'), ('ka', 'ქართული'), ('kk', 'Қазақ'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', '한국어'), ...
Rjtsahu/School-Bus-Tracking
BusTrack/repository/models/UserType.py
Python
gpl-3.0
743
0
from sqlalchemy import Column, String, Integer from BusTrack.repository import Base, session from BusTrack.repositor
y.models import STRING_LEN_SMALL class UserType(Base): __tablename__ = 'user_type' id = Column(Integer, primary_key=True) role_name = Column(String(STRING_LEN_SMALL)) @staticmethod def __create_default_role__(): if session.query(UserType).count() != 0: return driver =...
admin.role_name = 'Admin' session.add(driver) session.add(parent) session.add(admin) session.commit() session.close()
maxspad/MGrader
autograder/modules/questions/timedsubproc.py
Python
bsd-3-clause
861
0.013937
import subprocess, threading from subprocess import PIPE class TimedSubProc (object): def __init__(self, cmd): self.cmd = cmd.split() self.process = None
def run(self, timeout=5, stdin=None, stdout=PIPE, stderr=PIPE): self.output = None def target(): self.process = subprocess.Popen(self.cmd, stdin=stdin, stdout=stdout, stderr=stderr) self.output = self.process.communicate() thread = threading.Thr...
Process timeout! Terminating...' self.process.terminate() thread.join() return False return (self.process.returncode, self.output[0], self.output[1])
Lorquas/dogtail
dogtail/utils.py
Python
gpl-2.0
14,664
0.002523
# -*- coding: utf-8 -*- """ Various utilities Authors: Ed Rousseau <rousseau@redhat.com>, Zack Cerza <zcerza@redhat.com, David Malcolm <dmalcolm@redhat.com> """ __author__ = """Ed Rousseau <rousseau@redhat.com>, Zack Cerza <zcerza@redhat.com, David Malcolm <dmalcolm@redhat.com> """ import os import sys import subpro...
ot taken: " + path) return path def run(string, timeout=config.runTimeout, interval=config.runInterval, desktop=None, dumb=False, appName=''): """ Runs an application. [For simple command execution such as 'rm *', use os.popen() or os.system()] If dumb is omitted or is False, polls at interval seconds...
from tree import root as desktop args = string.split() os.environ['GTK_MODULES'] = 'gail:atk-bridge' pid = subprocess.Popen(args, env=os.environ).pid if not appName: appName = args[0] if dumb: # We're starting a non-AT-SPI-aware application. Disable startup # detectio...
bluemini/kuma
vendor/packages/translate/lang/my.py
Python
mpl-2.0
1,082
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2013 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 Foundat
ion; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it
will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.or...
ZhuChara2004/MA-Summer-Practice-2016
homeworks/team-2/prof-test/backend/models/question.py
Python
gpl-3.0
438
0.004566
from sqlalchemy import Column, ForeignKey, Inte
ger, String from sqlalchemy.orm import relationship from answer import Answer from base import Base class Question(Base): __tablename__ = 'question' id = Column(Integer, primary_key=Tr
ue) question = Column(String(256)) answers = relationship('Answer', backref='question', lazy='dynamic') test_id = Column(Integer, ForeignKey('test.id'))
hamishcunningham/fishy-wifi
wegrow-cloudside/elf-data-collector/webserver4/server-again.py
Python
agpl-3.0
6,539
0.001682
########################################################################### # Concurrent WSGI server - webserver3h.py # # # # Tested with Python 2.7.9 on Ubuntu 14.04 & Mac OS X # ################...
elf.client_connection.close() SERVER_ADDRESS = (HOST, PORT) = '', 8888 def make_server(server_address, application): signal.signal(signal.SIGCHLD, grim_reaper) serve
r = WSGIServer(server_address) server.set_app(application) return server if __name__ == '__main__': if len(sys.argv) < 2: sys.exit('Provide a WSGI application object as module:callable') app_path = sys.argv[1] module, application = app_path.split(':') module = __import__(module) ap...
logandk/serverless-wsgi
setup.py
Python
mit
867
0.001153
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="serverless-wsgi", version="3.0.0", python_requires=">3.6", author="Logan Raarup", author_email="logan@logan.dk", description="Amazon AWS API Gateway WSGI wrapper", long_description...
n_content_type="text/markdown", url="https://github.com/logandk/serverless-wsgi", py_modules=["serverless_wsgi"], install_requires=["werkzeug>2"], classifiers=( "Development Status :: 5 - Production/Stable", "Programming Language :: Python :: 3", "Intended Audience :: Developers"...
proved :: MIT License", "Operating System :: OS Independent", ), keywords="wsgi serverless aws lambda api gateway apigw flask django pyramid", )
lmiccini/sos
sos/plugins/dpkg.py
Python
gpl-2.0
1,590
0
# Copyright (c) 2012 Adam Stokes <adam.stokes@canonical.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This pro...
ANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy
of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. from sos.plugins import Plugin, DebianPlugin, UbuntuPlugin class Dpkg(Plugin, DebianPlugin, UbuntuPlugin): """Debian Package Management """ plugin_n...
JPO1/python-docs-samples
appengine/ndb/modeling/relation_model_models_test.py
Python
apache-2.0
2,299
0
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
ge governing permissions and # limitations under the License. """Test classes for code snippet for modeling article.""" from google.appengine.ext import nd
b from tests import AppEngineTestbedCase from . import relation_model_models as models class ContactTestCase(AppEngineTestbedCase): """A test case for the Contact model with relationship model.""" def setUp(self): """Creates 1 contact and 1 company. Assuming the contact belongs to tmatsuo's ...
danielbair/aeneas
aeneas/validator.py
Python
agpl-3.0
28,502
0.001193
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, A...
whether user input is well
-formed. :param rconf: a runtime configuration :type rconf: :class:`~aeneas.runtimeconfiguration.RuntimeConfiguration` :param logger: the logger object :type logger: :class:`~aeneas.logger.Logger` """ ALLOWED_VALUES = [ # # NOTE disabling the check on language since now we su...
ccrisan/motioneye
motioneye/diskctl.py
Python
gpl-3.0
7,702
0.006492
# Copyright (c) 2013 Calin Crisan # This file is part of motionEye. # # motionEye 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. # #...
# add separate partitions that did not match any disk for partition in partitions_by_dev.values(): if partition.pop('unmatched', False): disks_by_dev[partition['target']] = partition partition['partitions'] = [dict(partition)] # prepare
flat list of disks disks = disks_by_dev.values() disks.sort(key=lambda d: d['vendor']) for disk in disks: disk['partitions'].sort(key=lambda p: p['part_no']) return disks def _list_disks_fdisk(): try: output = subprocess.check_output(['fdisk', '-l'], stderr=utils.DEV_NULL) ...
sourlows/rating-cruncher
src/lib/click/exceptions.py
Python
apache-2.0
6,390
0.000156
from ._compat import PY2, filename_to_ui, get_text_stderr from .utils import echo class ClickException(Exception): """An exception that Click can handle and show to the user.""" #: The exit code for this exception exit_code = 1 def __init__(self, message): if PY2: if message is n...
.. versionadded:: 4.0 :param param_type: a string that indicates the type of the parameter. The default is to inherit the parameter type from the given `param`. Valid values are ``'parameter'``, ``'option'`` or ``'argument'``. """ def ...
self.param_type = param_type def format_message(self): if self.param_hint is not None: param_hint = self.param_hint elif self.param is not None: param_hint = self.param.opts or [self.param.human_readable_name] else: param_hint = None if isinstanc...
mistalaba/cookiecutter-django
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/models.py
Python
bsd-3-clause
466
0
from django.contrib.auth.models import AbstractUser from django.db.models import CharField fr
om django.urls import reverse from django.utils.translation import ugettext_lazy as _ c
lass User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username})
shub0/algorithm-data-structure
python/sum_roof_to_leaf.py
Python
bsd-3-clause
1,428
0.002101
#! /usr/bin/python ''' Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / \ 2 3 The root-to-leaf path 1->2 represen...
if not root.left and not root.right:
return True return False def inOrderTraversal(self, root, currentPath, path): if not root: return # visit() currentPath = 10 * currentPath + root.val if self.leafNode(root): path.append(currentPath) else: self.inOrderTraversal...
gabriel-samfira/jrunner
jrunner/jobqueue/workers/__init__.py
Python
apache-2.0
1,084
0
# Copyright 2013 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use
this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY...
ssions and limitations # under the License. import importlib from jrunner.common import * from oslo.config import cfg opts = [ cfg.StrOpt( 'worker_module', default='jrunner.jobqueue.workers.simple', help='Worker module'), ] CONF = cfg.CONF CONF.register_opts(opts, 'jobqueue') def get_wo...
wasit7/PythonDay
django/mysite2/mysite2/settings.py
Python
bsd-3-clause
3,183
0.001257
""" Django settings for mysite2 project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # B...
wto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'f@d3+wz7y8uj!+alcvc!6du++db!-3jh6=vr(%z(e^2n5_fml-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INST
ALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myauthen', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sess...
endlessm/chromium-browser
tools/swarming_client/third_party/httplib2/python3/httplib2/iri2uri.py
Python
bsd-3-clause
4,153
0.000963
# -*- coding: utf-8 -*- """Converts an IRI to a URI.""" __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = [] __version__ = "1.0.0" __license__ = "MIT" import urllib.parse # Convert an IRI to a URI following the rules in RFC 3987 # # The characters we n...
rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt", "ldap://
[2001:db8::7]/c=GB?objectClass?one", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", ] ...
gygcnc/gygcnc
gygcnc/image_gallery/admin.py
Python
bsd-3-clause
255
0.003922
from django.c
ontrib import admin from .models import Gallery, Photo class PhotoInline(admin.StackedInline): model = Photo extra = 1 class GalleryAdmin(admin.ModelAdmin):
inlines = [PhotoInline] admin.site.register(Gallery, GalleryAdmin)
tmc/mutter
mutter/notifiers.py
Python
bsd-2-clause
1,358
0.003682
import os import platform import subprocess class SoundPlayer: """Simple audio file player, invokes afplay on macs, mpg123 otherwise.""" def __init__(self): self.basedir = os.path.dirname(__file__) self.sounds = { 'startup': 'run.mp3', 'shutdown': 'quit.mp3', ...
ly to implement notify" def notify(self, event): raise NotImplementedError() class TextNotifier(object): "Basic text notifier" def notify(self, event): print 'Notify: ', event class SoundNotifier(object): "Simple notifier that uses SoundPlayer"
def __init__(self): self.player = SoundPlayer() def notify(self, event): print 'mutter: %s' % event if event in self.player.sounds: self.player.play(event)
rg3/youtube-dl
youtube_dl/extractor/toggle.py
Python
unlicense
8,970
0.0019
# coding: utf-8 from __future__ import unicode_literals import json import re from .common import InfoExtractor from ..utils import ( determine_ext, ExtractorError, float_or_none, int_or_none, parse_iso8601, strip_or_none, ) class ToggleIE(InfoExtractor): IE_NAME = 'toggle' _VALID_UR...
% vid_format, fatal=False) for f in m3u8_formats: # Apple FairPlay Streaming if '/fpshls/' in f['url']: continue formats.append(f) elif ext == 'mpd': formats.extend(self._e...
note='Downloading %s MPD manifest' % vid_format, errnote='Failed to download %s MPD manifest' % vid_format, fatal=False)) elif ext == 'ism': formats.extend(self._extract_ism_formats( video_url, video_id, ism_id=vid_format, ...
Acehaidrey/incubator-airflow
tests/providers/amazon/aws/operators/test_s3_delete_objects.py
Python
apache-2.0
3,825
0.003137
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
): bucket = "testbucket" key = "path/data.txt" conn = boto3.client('s3') conn.create_bucket(Bucket=bucket) conn.upload_fileobj(Bucket=bucket, Key=key, Fileobj=io.BytesIO(b"input")) # The obj
ect should be detected before the DELETE action is taken objects_in_dest_bucket = conn.list_objects(Bucket=bucket, Prefix=key) assert len(objects_in_dest_bucket['Contents']) == 1 assert objects_in_dest_bucket['Contents'][0]['Key'] == key op = S3DeleteObjectsOperator(task_id="test_task_s...
piratecb/up1and
app/main/__init__.py
Python
mit
98
0.010204
from flask import Blu
eprint main = Blueprint('main', __name__) fro
m . import views, errors
JohnVinyard/zounds
zounds/datasets/predownload.py
Python
mit
250
0
from io import BytesIO class P
reDownload(BytesIO): def __init__(self, initial_bytes, url): super(PreDownload, self).__init__(initial_bytes) if not url: r
aise ValueError('url must be provided') self.url = url
altnight/individual-sandbox
diary/20171022/sample/auth_sample/server.py
Python
apache-2.0
1,243
0.006436
from flask import Flask, request, redirect, url_for app = Flask(__name__) logged_in = False LOGIN_TEMPLATE = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form method="POST" action=""> <input type="text" name="username"> <input type="password" name="...
ef two(): return "two" @app.route("/login", methods=["GET", "POST"]) def login(): global logged_in if logged_in: return redirect(url_for("mypage")) if request.method == "GET": return LOGIN_TEMPLATE if not request.form.get("username") or not request.form.get("password"): retu...
if not logged_in: return redirect(url_for("login")) return "mypage" @app.route("/logout") def logout(): global logged_in if not logged_in: return redirect(url_for("login")) logged_in = False return "logout" def main(): app.run(debug=True) if __name__ == "__main__": main(...
assefay/inasafe
safe_qgis/ui/options_dialog_base.py
Python
gpl-3.0
23,148
0.003629
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'options_dialog_base.ui' # # Created: Mon Feb 17 11:50:09 2014 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 e...
)) self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents")) self.gridLayout = QtGui.QGridLayout(
self.scrollAreaWidgetContents) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.cbxVisibleLayersOnly = QtGui.QCheckBox(self.scrollAreaWidgetContents) self.cbxVisibleLayersOnly.setObjectName(_fromUtf8("cbxVisibleLayersOnly")) self.gridLayout.addWidget(self.cbxVisibleLayersOnly,...
blackjax-devs/blackjax
setup.py
Python
apache-2.0
1,650
0.000606
import codecs import os.path import sys import setuptools # READ README.md for long description on PyPi. try: long_description = open("README.md", encoding="utf-8").read() except Exception as e: sys.stderr.write(f"Failed to read README.md:\n {e}\n") sys.stderr.flush() long_description
= "" # Get the package's version number
of the __init__.py file def read(rel_path): """Read the file located at the provided relative path.""" here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, rel_path), "r") as fp: return fp.read() def get_version(rel_path): """Get the package's version number. ...
supernifty/mgsa
mgsa/count_homopolymers.py
Python
mit
550
0.038182
i
mport collections import itertools import sys def count_homopolymers( fh ): s = [] print "building..." for line in fh: if line.startswith( '>' ): continue s.append( line.strip() ) print "counting..." runs = collections.defaultdict(int) best = collections.defaultdict(int) last = None for ...
t: runs[last] = 0 last = c return best if __name__ == '__main__': print count_homopolymers( sys.stdin )
sahilshekhawat/sympy
sympy/plotting/tests/test_plot.py
Python
bsd-3-clause
8,460
0.002719
from sympy import (pi, sin, cos, Symbol, Integral, summation, sqrt, log, oo, LambertW, I, meijerg, exp_polar, Max) from sympy.plotting import (plot, plot_parametric, plot3d_parametric_line, plot3d, plot3d_parametric_surface) from sympy.plotting.plot import unset_show from ...
p = plot3d(-x * y, x * y, (x, -5, 5)) p.save(tmp_file('%s_surface_multiple' % name)) # Multiple 3D plots with different ranges. p = plot3d( (x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3))) p.save(tmp_file('%s_surface_multiple_ranges' % name)) # Single Parametric 3D plot...
ts. p = plot3d_parametric_surface( (x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)), (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5))) p.save(tmp_file('%s_parametric_surface' % name)) ### # Examples from the 'colors' notebook ### p = plot(sin(x)) p[0].line_color = lam...
osuripple/lets
pp/__init__.py
Python
agpl-3.0
272
0
from common.constants import gameModes
from pp import ez from pp import wifipiano3 from pp import cicciobello PP_CALCULATORS = { gameModes.STD: ez.Ez, gameModes.TAIKO: ez.Ez, gameModes.CTB: cicciobello.Cicciobello, gam
eModes.MANIA: wifipiano3.WiFiPiano }
felipewaku/compiladores-p2
lambda_compiler/__main__.py
Python
mit
195
0.010256
from
compiler.compiler import LambdaCompiler d
ef main(): f = open('input.txt', 'r') compiler = LambdaCompiler(f) compiler.perform('output.py') if __name__ == "__main__": main()
marcore/pok-eco
xapi/patterns/manage_wiki.py
Python
agpl-3.0
1,746
0.001145
import re from django.conf import settings from tincan import ( Activity, ActivityDefinition, LanguageMap ) from xapi.patterns.base import BasePattern from xapi.patterns.eco_verbs import ( LearnerCreatesWikiPageVerb, LearnerEditsWikiPageVerb ) class BaseWikiRule(BasePattern): # pylint: disable=ab...
Verb): def match(self, evt, course_id): return re.match( '/courses/'+settin
gs.COURSE_ID_PATTERN+r'/wiki/\w+/_edit/?', evt['event_type'])
narayanaditya95/aldryn-wow
aldryn_wow/south_migrations/0001_initial.py
Python
bsd-3-clause
5,058
0.007513
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Animation' db.create_table(u'aldryn_wow_animation', ( ...
offset', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)), ('iteration', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)), )) db.send_create_signal(u'aldryn_wow', ['WOWAnimation']) def backwards(self, orm
): # Deleting model 'Animation' db.delete_table(u'aldryn_wow_animation') # Deleting model 'WOWAnimation' db.delete_table(u'aldryn_wow_wowanimation') models = { u'aldryn_wow.animation': { 'Meta': {'object_name': 'Animation', '_ormbases': ['cms.CMSPlugin']}, ...
REBradley/WineArb
winearb/articles/serializers.py
Python
bsd-3-clause
435
0.002299
f
rom rest_framework
import serializers from ..upload_handling.serializers import ArticleImageSerializer class ArticleSerializer(serializers.Serializer): main_title = serializers.CharField(max_length=255) sub_title = serializers.CharField(max_length=255) author = serializers.CharField(max_length=255) image = ArticleImageS...
hfp/tensorflow-xsmm
tensorflow/contrib/gan/python/features/python/spectral_normalization_impl.py
Python
apache-2.0
12,318
0.003491
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
te_spectral_norm( weights, power_iteration_rounds=power_iteration_rounds), name=name) return sn def _default_name_filter(name): """A filter function to identify common names of weight variables. Args: name: The variable name. Returns: Whether `name` is a standard name for a ...
name) return match is not None def spectral_normalization_custom_getter(name_filter=_default_name_filter, power_iteration_rounds=1): """Custom getter that performs Spectral Normalization on a weight tensor. Specifically it divides the weight tensor by its largest singul...
LLNL/spack
var/spack/repos/builtin/packages/pygmo/package.py
Python
lgpl-2.1
1,202
0.002496
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifi
er: (Apache-2.0 OR M
IT) from spack import * class Pygmo(CMakePackage): """Parallel Global Multiobjective Optimizer (and its Python alter ego PyGMO) is a C++ / Python platform to perform parallel computations of optimisation tasks (global and local) via the asynchronous generalized island model.""" homepage = "https...
viaict/viaduct
app/forms/examination.py
Python
mit
1,224
0
from app import constants from flask_babel import lazy_gettext as _ from flask_wtf import FlaskForm from flask_wtf.file import FileField from wtforms import StringField, SelectField, DateField from wtforms.validators import InputRequired, Optional from app.models.examination import test_type_default class CourseForm...
ption = StringField(_('Description')) class EducationForm(FlaskForm): title = StringField(_('Title'), validators=[InputRequired()])
class EditForm(FlaskForm): date = DateField(_('Date'), validators=[Optional()], format=constants.DATE_FORMAT) course = SelectField(_('Course'), coerce=int, validators=[InputRequired()]) education = SelectField(_('Education'), coerce=int, ...
synergeticsedx/deployment-wipro
openedx/core/djangoapps/monitoring/startup.py
Python
agpl-3.0
131
0
""" Registers signal handlers at startup. """ # pylint: disable=unused-import import openedx.core.djangoapps.monit
oring.except
ions
hackday-profilers/flocker
flocker/dockerplugin/_script.py
Python
apache-2.0
3,412
0
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Command to start up the Docker plugin. """ from os import umask from stat import S_IRUSR, S_IWUSR, S_IXUSR from twisted.python.usage import Options from twisted.internet.endpoints import serverFromString from twisted.application.internet import StreamServe...
# listening on Unix socket, e.g. # https://twistedmatrix.com/trac/ticket/5406 "fix" that by # pretending we have a port number. Yes, I feel guilty. UNIXAddress.port = 0 # We can use /etc/flocker/agent.yml and /etc/flocker/node.crt to load # some information we need: ...
t_config['control-service']['hostname'] node_id = agent_config['node-credential'].uuid certificates_path = options["agent-config"].parent() control_port = options["rest-api-port"] flocker_client = FlockerClient(reactor, control_host, control_port, ...
hwaf/hwaf
py-hwaftools/orch/tools.py
Python
bsd-3-clause
7,185
0.010717
#!/usr/bin/env python ''' Main entry to worch from a waf wscript file. Use the following in the options(), configure() and build() waf wscript methods: ctx.load('orch.tools', tooldir='.') ''' def options(opt): opt.add_option('--orch-config', action = 'store', default = 'orch.cfg', help='G...
help='Set the section to start the orchestration') def configure(cfg): import orch.configure orch.configure.configure(cfg) def build(bld): import orch.build orch.build.build(bld) # the stuff below is for augmenting waf import time from orch.wafutil import exec_command from orch.util impo...
ource_dir}', prepare = '{build_dir}', build = '{build_dir}', install = '{build_dir}', ) # Main interface to worch configuration items class WorchConfig(object): def __init__(self, **pkgcfg): self._config = pkgcfg def __getattr__(self, name): return self._config[name] def get(se...
kammmoun/PFE
codes/Ewens&uniform+RSK_rho_1.py
Python
apache-2.0
2,011
0.03083
# -*- coding: utf-8 -*- """ Created on Thu Apr 27 13:35:59 2017 @author: mkammoun.lct """ import numpy as np import matplotlib.pyplot as pl from bisect import bisect import math n=200 n2=10000 def per(theta,n): perm=[] for i in range(1,n+1): if np.random.binomial(1,theta/(float(th...
erm[j] perm[j]=i perm.append(k) return perm per(0.1,1000) def RSK(p): '''Given a permutation p, spit out a pair of Young tableaux''' P = []; Q = [] def insert(m, n=0): '''Insert m into P, then place n in Q at the same place''' for r in range(len(P)...
m,P[r][c] P.append([m]) return P for i in range(len(p)): insert(int(p[i]), i+1) return map(len,P) def pointspos(per): rsk=RSK(per) return [rsk[i]-i-1 for i in range(len(rsk)) if (rsk[i]-i -1) >=0] pointspos([1,2,3]) ## seulement les points entre [-3 rac(n) et ...
epochblue/nanogen
tests/test_models.py
Python
mit
10,406
0.001057
import datetime import os from unittest import mock import pytest from nanogen import models example_post = """\ # Test Post And this is my _markdown_ **content**. Look, it also has: * an * unordered * list """ example_config = """\ [site] author = Example user email = user@example.com description = A test desc...
ts(tmpdir): path = tmpdir.mkdir('blog') preview_path = path.mkdir('_preview') # Set up a nanogen blog for posts blog = models.Blog(str(path)) blog.init() wit
h mock.patch('subprocess.call'): blog.new_post('Test post', draft=False) blog.new_post('Draft post', draft=True) post_template = path.join('_layout').join('post.html') post_template.write("""\ <!doctype html> <html> <body>Post template would go here.</body> </html> """) ...
adrienverge/yamllint
tests/test_yamllint_directives.py
Python
gpl-3.0
17,973
0
# -*- coding: utf-8 -*- # Copyright (C) 2016 Adrien Vergé # # 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 pro...
self.conf, problem1=(3, 18, 'trailing-spaces'), problem2=(4, 8, 'colons'), problem3=(6, 7, 'colons'), problem4=(6, 26, 'trailing-spaces')) self.check('---\n' '- [valid , YAML]\n' '- trailing spac...
ercius/openNCEM
ncempy/algo/distortion.py
Python
gpl-3.0
8,278
0.010993
""" Module to handle distortions in diffraction patterns. """ import numpy as np import scipy.optimize def filter_ring(points, center, rminmax): """Filter points to be in a certain radial distance range from center. Parameters ---------- points : np.ndarray Candidate points. ...
np.array(center) center = np.reshape(center, 2) except: raise TypeError('Something wrong with the input!') # calculate radii rs = np.sqrt( np.square(points[:,0]-center[0]) + np.square(points[:,1]-center[1]) ) # calculate angle thes = np.arctan2(points[:,1]-center[1], points[...
or minimizing the deviations from the mean radial distance. Parameters ---------- param : np.ndarray The center to optimize. data : np.ndarray The points in x,y coordinates of the original image. Returns ------- : np.ndarray Residuals. ""...
jasonsbrooks/ARTIST
src/artist_generator/analyze/chords.py
Python
mit
10,666
0.008063
from db import get_engines,get_sessions,Song,Track,Note from iter import TimeIterator from utils import Counter from sqlalchemy.orm import sessionmaker from preference_rules import * import music21,sys from optparse import OptionParser from multiprocessing import Process,Queue class ChordSpan(object): """ A ...
te in ts.notes(): res.append(note) return res def roman_numeral(self,track): """ Calculate the roman numeral corresponding to the computed root and key of the corresponding track Args: track: The track to w
hich a Note in this ChordSpan belongs. Note: Here we assume that at any moment in time, there is only one key signature in all tracks of the song. Returns: the Music21 Roman Numeral object. """ pitch = music21.key.sharpsToPitch(track.key_sig_top) key = music21.k...
EmanueleCannizzaro/scons
src/engine/SCons/Tool/MSCommon/sdk.py
Python
mit
14,245
0.00702
# # Copyright (c) 2001 - 2016 The SCons Foundation # # 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...
host_arch, target_arch)) file=self.vc_setup_scripts.get(arch_string,None) debug("sdk.py: get_sdk_vc_script():file:%s"%file) return file class WindowsSDK(SDKDefinition): """ ...
__(self, *args, **kw): SDKDefinition.__init__(self, *args, **kw) self.hkey_data = self.version class PlatformSDK(SDKDefinition): """ A subclass for trying to find installed Platform SDK directories. """ HKEY_FMT = r'Software\Microsoft\MicrosoftSDK\InstalledSDKS\%s\Install Dir' def _...
beckjake/python3-hglib
tests/test-paths.py
Python
mit
512
0.001953
from . import common import os import hglib class test_paths(common.basetest): def test_basic(self): f =
open('.hg/hgrc', 'a') f.write('[paths]\nfoo = bar\n') f.close() # hgrc isn't watch
ed for changes yet, have to reopen self.client = hglib.open() paths = self.client.paths() self.assertEquals(len(paths), 1) self.assertEquals(paths['foo'], os.path.abspath('bar')) self.assertEquals(self.client.paths('foo'), os.path.abspath('bar'))
crmccreary/openerp_server
openerp/addons/document_ftp/wizard/ftp_browse.py
Python
agpl-3.0
2,556
0.004304
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
context=None): data_id = ids and ids[0] or False data = self.browse(cr, uid, data_id, context=context) final_url = data.url return { 'type': 'ir.actions.act_url',
'url':final_url, 'target': 'new' } document_ftp_browse() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Cloudlie/pythonlearning
ex18.py
Python
mit
514
0.015564
# this one is like your scripts with argv def print_two(*args): arg1,arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually pointless, we can just do this def print_tw
o_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # this just takes one arguments def print_one(arg1): print "arg1: %r" % arg1 # this just takes no arguments def print_none(): print "I got nothin'." print_two("Zed", "Shaw
") print_two_again("Zed", "Shaw") print_one("First") print_none()
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractCnoveltranslationsCom.py
Python
bsd-3-clause
784
0.026786
def extractCnoveltranslationsCom(item): ''' Parser for 'cnoveltranslations.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None
tagmap = [ ('what if my brother is too good?', 'What if My Brother is Too Good?', 'translated'), ('i am this type of woman', 'I Am Th
is Type of Woman', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, po...
DanteOnline/free-art
venv/bin/painter.py
Python
gpl-3.0
2,138
0.000935
#!/home/dante/Projects/free-art/venv/bin/python3 # # The Python Imaging Library # $Id$ # # this demo script illustrates pasting into an already displayed # photoimage. note that the current version of Tk updates the whole # image every time we paste, so to get decent performance, we split # the image into a set of til...
cept KeyError: pass # outside the image self.update_idletasks() # # main if len(sys.argv) != 2: print("Usage: painter file") sys.exit(1) root = Tk() im = Image.open(sys.argv[
1]) if im.mode != "RGB": im = im.convert("RGB") PaintCanvas(root, im).pack() root.mainloop()
MattPerron/esper
esper/query/management/commands/gender_tracks.py
Python
apache-2.0
2,055
0.001946
from django.core.management.base import BaseCommand from faceDB.face_db import FaceDB from faceDB.face import FaceCluster from faceDB.util import * # only required for saving cluster images from carnie_helper import RudeCarnie from query.models import * import random import json class Command(BaseCommand): help ...
= 0 if path == '': return video = Video.objects.filter(path=path).get() labelset = video.detected_labelset() tracks = Track.objects.filter(first_frame__labelset=labelset).all() for track in tracks:
if track.gender != '0': print 'skipping_track', track.id continue faces = Face.objects.filter(track=track) print track.id print("len of faces for path {}, is {}".format(path, len(faces))) imgs = ['./assets...
welltempered/rpy2-heroku
rpy/robjects/tests/__init__.py
Python
gpl-2.0
1,832
0.003821
import unittest import testRObject import testVector import testArray import testDataFrame import testFormula import testFunction import testEnvironment import testRobjects import testMethods import testPackages import testHelp import testLanguage # wrap this nicely so a warning is issued if no numpy present import t...
ges = testPackages.suite() suite_Help = testHelp.suite() suite_Language = testLanguage.suite() alltests = unittest.TestSuite([suite_RObject, suite_Vector, suite_Array, suite_DataFrame,...
suite_Robjects, suite_Methods, suite_NumpyConversions, suite_Packages, suite_Help, suite_Language ]) ...
Lapin-Blanc/AS_STAGES
django_calendar/views.py
Python
mit
8,052
0.007211
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.utils import formats, dateparse, timezone from .models import Period, Traineeship, Student from django.core.exceptions import ValidationError from datetime import datetime, d...
.combine(dateparse.parse_date(request.GET['end']), datetime.min.time())) base_criteria = { 'traineeship' : traineeship } if request.GET['type']=='past': base_criteria['start__gte'] = time_start base_criteria['end__lt'
] = time_limit() if request.GET['type']=='future': base_criteria['start__gte'] = time_limit() base_criteria['end__lt'] = time_end ps = Period.objects.filter(**base_criteria) d = [] for p in ps: d.append({ 'id': p.id, ...
SKA-ScienceDataProcessor/legion-sdp-clone
language/travis.py
Python
apache-2.0
2,295
0.004793
#!/usr/bin/env python # Copyright 2015 Stanford University # # 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 applicabl...
assert shasum.wait() == 0 subprocess.check_call(['tar', 'xfJ', clang_tarball]) env.update({ 'PATH': ':'.join( [os.path.join(clang_dir, 'bin'), os.environ['PATH']]), 'DYLD_LIBRARY_PATH': ':'.join( [os.path.join(clang_dir, 'lib')] + ...
}) return env def test(root_dir, install_args, install_env): subprocess.check_call( ['./install.py'] + install_args, env = install_env, cwd = root_dir) subprocess.check_call( ['./test.py'], cwd = root_dir) if __name__ == '__main__': root_dir = os.path.realpath...