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
gandrewstone/yadog
PyHtmlGen/json.py
Python
gpl-3.0
2,038
0.034838
from htmldoc import * from chunk import * from module import * from js import * #? This global variable is used to specify where the javascript files are on the server. JavascriptDir = "./" #<_ view="internal">A Marker showing where the RPCs are installed</_> rpcim = Marker("js") rpcs=[""" <script language='JavaScri...
gen.WriteFile("testjson.html",d) #</examp
le>
commtrack/commtrack-core
apps/django_tables/tests/test_templates.py
Python
bsd-3-clause
5,249
0.004585
"""Test template specific functionality. Make sure tables expose their functionality to templates right. This generally about testing "out"-functionality of the tables, whether via templates or otherwise. Whether a test belongs here or, say, in ``test_basic``, is not always a clear-cut decision. """ from django.temp...
: row['tld'], row['cc'], row['population'] # certain data is available on columns assert countries.columns['currency'].sortable == True assert countries.columns['capital'].sortable == F
alse assert countries.columns['name'].visible == True assert countries.columns['tld'].visible == False def test_render(): """For good measure, render some actual templates.""" class CountryTable(tables.Table): name = tables.TextColumn() capital = tables.TextColumn() population ...
chubbymaggie/datasketch
benchmark/lshensemble_benchmark.py
Python
mit
10,558
0.004262
""" Benchmark dataset from: https://github.com/ekzhu/set-similarity-search-benchmark. Use "Canada US and UK Open Data": Indexed sets: canada_us_uk_opendata.inp.gz Query sets (10 stratified samples from 10 percentile intervals): Size from 10 - 1k: canada_us_uk_opendata_queries_1k.inp.gz Size fro...
", action="store_true") parser.add_argument("--use-asym-minhash", action="store_true") parser.add_argument("--use-redis", action="store_true") parser.add_argument("--redis-host", type=str, default="localhost") parser.add_argument("--redis-port", type=int, default=6379) args = parser.parse_args(sys.a...
index_data_cache = "{}.pickle".format(args.indexed_sets) query_data_cache = "{}.pickle".format(args.query_sets) if os.path.exists(index_data_cache): print("Using cached indexed sets {}".format(index_data_cache)) with open(index_data_cache, "rb") as d: index_data = pickle.load(d) ...
DayGitH/Python-Challenges
DailyProgrammer/DP20120709A.py
Python
mit
2,709
0.005537
""" The Fibonacci numbers, which we are all familiar with, start like this: 0,1,1,2,3,5,8,13,21,34,... Where each new number in the sequence is the sum of the previous two. It turns out that by summing different Fibonacci numbers with each other, you can create every single positive integer.
In fact, a much stronger statement holds: Every single positive integer can be represented in one and only one way as a sum of non-consecutive Fibonacci numbers. This is called the number's "Zeckendorf representation" [http://en.wikipedia.org/wiki/Zeckendorf%27s_theorem]. For instance, the Zeckendorf representation o...
umbers are Fibonacci numbers, and that they are non-consecutive (i.e. no two numbers in a Zeckendorf representation can be next to each other in the Fibonacci sequence). There are other ways of summing Fibonacci numbers to get these numbers. For instance, 100 is also equal to 89 + 5 + 3 + 2 + 1, but 1, 2, 3, 5 are all...
thomasbilk/django-filer
filer/fields/file.py
Python
bsd-3-clause
5,490
0.002186
#-*- coding: utf-8 -*- import inspect from django import forms from django.conf import settings as globalsettings from django.contrib.admin.widgets import ForeignKeyRawIdWidget from django.contrib.admin.sites import site from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import revers...
els import File from filer import settings
as filer_settings import logging logger = logging.getLogger(__name__) class AdminFileWidget(ForeignKeyRawIdWidget): choices = None def render(self, name, value, attrs=None): obj = self.obj_for_value(value) css_id = attrs.get('id', 'id_image_x') css_id_thumbnail_img = "%s_thumbnail_im...
0x00ach/zer0m0n
signatures/sniffer_winpcap.py
Python
gpl-3.0
1,246
0.00321
# Copyright (C) 2012 Thomas "stacks" Birn (@stacksth) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
U General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from lib.cuckoo.common.abstracts import Signature class InstallsWinpcap(Signature): name = "sniffer_winpcap" description = "Installs WinPCAP" severity = 3 categories = ["sniffer"] authors = ["Thomas Bi...
ex"] minimum = "0.5" def run(self): indicators = [ ".*\\\\packet\.dll$", ".*\\\\npf\.sys$", ".*\\\\wpcap\.dll$" ] for indicator in indicators: if self.check_file(pattern=indicator, regex=True): return True return ...
cantino/newspaper
newspaper/urls.py
Python
mit
9,141
0.004376
# -*- coding: utf-8 -*- """ Newspaper treats urls for news articles as critical components. Hence, we have an entire module dedicated to them. """ __title__ = 'newspaper' __author__ = 'Lucas Ou-Yang' __license__ = 'MIT' __copyright__ = 'Copyright 2014, Lucas Ou-Yang' import logging import re from urlparse import ( ...
proper_url = urljoin(source_url, url) proper_url = redirect_back(proper_url, source_domain) proper_url = remove_args(proper_url) else: proper_url = remove_args(url) except ValueError, e: log.critical('url %s failed on err %s' % (url, str(e))) # print '...
ck on an absolute url. First, perform a few basic checks like making sure the format of the url is right, (scheme, domain, tld). Second, make sure that the url isn't some static resource, check the file type. Then, search of a YYYY/MM/DD pattern in the url. News sites love to use this pattern...
wolfiex/DSMACC-testing
zgraph.py
Python
gpl-3.0
2,805
0.023173
import networkx as nx import numpy as np import pandas as pd def normalise(x): x = x[:]#deepcopy error x -= min(x) x /= max(x) return x def jgraph(posjac): ''' networkx graph object from posjac at timestep ''' posjac = 1 - normalise(np.log10(posjac).replace([np.inf,-np.inf],np.nan...
t[0]}) return rt def metric(GS,met = 'nx.pagerank'): ''' GS - out array from to_graph ''' metfn = eval(met) for gt in range(len(GS)): res = metfn(GS[gt]['graph']) res = [[key, res[key]] for key, value in sorted(res.iteritems(), key=lambda k,v: (v,k))]
GS[gt][met] = res return GS def geobj2df(GS,what = 'nx.pagerank'): res = [] index = [] for s in GS: index.append(s['time']) s = pd.DataFrame(s[what]) s.index = s[0] s=s[1] res.append(s) df = pd.concat(res,axis = 1).T df.index = index df = (df*1.1...
wpoely86/easybuild-easyblocks
easybuild/easyblocks/q/quantumespresso.py
Python
gpl-2.0
15,419
0.003178
## # Copyright 2009-2016 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # Flemish Research Foundation ...
if keep: line = re.sub(r"^(%s\s*=[ \t]*)(.*)$" % k, r"\1\2 %s" % v, line) else: line = re.sub(r"^(%s\s*=[ \t]*).*$" % k, r"\1%s" % v, line) # fix preprocessing directives for .f90 files in make.sys if required ...
\) -c \$<", "$(CPP) -C $(CPPFLAGS) $< -o $*.F90\n" + "\t$(MPIF90) $(F90FLAGS) -c $*.F90 -o $*.o", line) sys.stdout.write(line) except IOError, err: raise EasyBuildError("Failed to p...
Magicked/crits
crits/dashboards/views.py
Python
mit
14,127
0.00446
import json from django.contrib.auth.decorators import user_passes_test try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import render from crits.core.user_tools import user_can_view_data from crits...
hes = True, skip=tableId) dashboard = newDash clone = True newDashName = newDash.name elif dashboard.isPublic: updateChildren(dashboard.id) else: errorMessage = "Error finding dashboard. Please refresh and try again." ex...
at name." if errorMessage: return respondWithError(errorMessage, True) userId = request.GET.get('userId', None) tableName = request.GET.get('tableName', None) searchTerm = request.GET.get('query', None) objType = request.GET.get('object_type', None) columns = json.loads(request.GET.get("...
rdo-management/heat
heat/api/cfn/v1/signal.py
Python
apache-2.0
2,047
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
resource_name=identity.resource_name, details=body) except Exception as ex: return exception.map_remote_error(ex) def create_resource(options): """ Signal resource factory method. """ de
serializer = wsgi.JSONRequestDeserializer() return wsgi.Resource(SignalController(options), deserializer)
sdpython/ensae_teaching_cs
_todo/pvalues/pvalues_sigma.py
Python
mit
2,697
0.071932
import numpy, matplotlib, random, pylab, math def matrix_square_root(sigma) : eigen, vect = numpy.linalg.eig(sigma) dim = len(sigma) res = numpy.identity(dim) for i in range(0,dim) : res[i,i] = eigen[i]**0.5 return vect * res * vect.transpose() def chi2_level (alpha = 0.95) : N = 1...
5) * a*2 ) y.append ( a ) x.append ( (random.random ()-0.5) * a*2 ) y.append ( -a ) x.append ( (random.random ()-0.5
) * a*2 ) xs,ys = [],[] for a,b in zip (x,y) : ar = numpy.matrix( [ [a], [b] ] ).transpose() we = ar * root xs.append ( we [0,0] ) ys.append ( we [0,1] ) pylab.plot(xs,ys, 'bo') pylab.show() def circle_figure (mat, a) : x = [ ] y = [ ] for ...
cactusbin/nyt
matplotlib/examples/statistics/errorbar_demo.py
Python
unlicense
200
0.005
""" Demo of the errorb
ar function. """ import numpy as np import matplotlib.pyplot as plt
# example data x = np.arange(0.1, 4, 0.5) y = np.exp(-x) plt.errorbar(x, y, xerr=0.2, yerr=0.4) plt.show()
naitoh/py2rb
tests/strings/split.py
Python
mit
266
0.003759
s="the quick brown fox jumped over the lazy dog" t = s.split(" ") for v
in t: print(v) r = s.split("e") for v in r: print(v) x = s.split() for v in x: print(v) #
2-arg version of split not supported # y = s.split(" ",7) # for v in y: # print v
gpndata/cattle
tests/integration/cattletest/core/test_cluster.py
Python
apache-2.0
6,493
0
from common_fixtures import * # NOQA def _clean_clusterhostmap_for_host(host): for cluster in host.clusters(): cluster.removehost(hostId=str(host.id)) def _resource_is_inactive(resource): return resource.state == 'inactive' def _resource_is_active(resource): return resource.state == 'active' ...
nt.wait_success(cluster.deactivate()) cluster = super_client.wait_success(super_client.delete(cluster)) cluster = super_client.wait_success(cluster.purge()) # check no hosts is registered to this cluster wait_for_condition( super_client, cluster, lambda x: len(x.hosts()) == 0) # verify tha...
da x: 'State is: ' + x.state) # verify that the agent instance is removed as well agent_instances = super_client.list_instance(agentId=agentId) wait_for_condition( super_client, agent_instances[0], lambda x: x.state == 'removed', lambda x: 'State is: ' + x.state) @pytest.mark.skip...
drawquest/drawquest-web
website/canvas/migrations/0021_auto__chg_field_comment_parent_content__chg_field_comment_reply_conten.py
Python
bsd-3-clause
9,191
0.007399
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Renaming column for 'Comment.parent_content' to match new field type. db.rename_column('canvas_comment',...
'}, 'content_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'post': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'thread': ('django.db.models.fields.relate...
ForeignKey', [], {'to': "orm['canvas.Thread']", 'null': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canv
stackforge/cloudkitty
cloudkitty/rating/pyscripts/datamodels/script.py
Python
apache-2.0
1,854
0
# -*- coding: utf-8 -*- # Copyright 2015 Objectif Libre # # 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 ...
50b5715d' 'c83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec' '2f63b931bd47417a81a538327af927da3e') return sample class ScriptCollection(wtypes.Base): """Type describing a list of scripts. """ scripts = [Script] """List of scripts."""...
ple = Script.sample() return cls(scripts=[sample])
laroque/couchdb-python3
couchdb/tests/testutil.py
Python
bsd-3-clause
1,378
0.000726
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2009 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have rece
ived as part of this distribution. import random import sys from couchdb import client from couchdb import ServerError class TempDatabaseMixin(object): temp_dbs = None _db = None def setUp(self): self.server = client.Server(full_commit=False) def tearDown(self): if self.temp_dbs: ...
self.server.delete(name) except ServerError as err: if err.args[0] == (500, ('error', 'eacces')): continue raise def temp_db(self): if self.temp_dbs is None: self.temp_dbs = {} # Find an unused database...
adlr/naclports
build_tools/naclports.py
Python
bsd-3-clause
7,198
0.010975
#!/usr/bin/env python # Copyright (c) 2013 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Library for manipulating naclports packages in python. This library can be used to build tools for working with naclports p...
ive = self.DownloadLocation() ext = os.path.splitext(archive)[1] if ext in ('.gz', '.tgz', '.bz2'): cmd = ['tar', 'xf', archive, '-C', t
mp_output_path] elif ext in ('.zip',): cmd = ['unzip', '-q', '-d', tmp_output_path, archive] else: raise Error('unhandled extension: %s' % ext) print cmd subprocess.check_call(cmd) src = os.path.join(tmp_output_path, new_foldername) dest = os.path.join(output_path, ne...
frdb194/ubuntu-tweak
ubuntutweak/janitor/chrome_plugin.py
Python
gpl-2.0
377
0.002653
from ubuntutweak.janitor import JanitorCachePlugin class ChromeCachePlugin(JanitorCachePlugin): __title__ = _('Chrome Cache') __category__ = 'application' root_path = '~/.cache/google-chrome/Default'
class ChromiumCachePlugin(JanitorCachePlugin): __title__ = _('Chromium Cache') __category__ = 'application' root_path = '~/.cache/chromium/De
fault'
chrisseto/osf.io
scripts/refresh_addon_tokens.py
Python
apache-2.0
3,392
0.003833
#!/usr/bin/env python # encoding: utf-8 import logging import math import time from django.utils import timezone import django from modularodm import Q from oauthlib.oauth2 import OAuth2Error from dateutil.relativedelta import relativedelta django.setup() from framework.celery_tasks import app as celery_app from sc...
delta = relativedelta(days=days) Provider = look_up_provider(addon) if not Provider: logger.error('Unable to find Provider cla
ss for addon {}'.format(addon)) else: main(delta, Provider, rate_limit, dry_run=dry_run)
barun-saha/ns2web
ns2trace/metrics.py
Python
gpl-2.0
8,308
0.011916
__author__= "barun" __date__ = "$20 May, 2011 12:19:25 PM$" ## Defines a collection of metrics that can be used to analyze the performance # of a network. class Metrics(object): ## Calculate average throughput as: total_bytes_rcvd / duration. # # @param pkts_list An iterator object in the...
turn result @staticmethod ## Calculate throughput as total bytes_rcvd upto current instance of time / total duration upto current instance
# @param pkts_list An iterator object in the format [(timestamp, size),] # @return A list in the form [(time_instance, total_bytes),] def cumulative_throughput(pkts_list=None): #print 'Current throughput' result = [] start_time = -1 # Anything less than 0 this_instance = 0...
sysbot/pastedown
vendor/pygments/tests/run.py
Python
mit
1,247
0.00401
# -*- coding: utf-8 -*- """ Pygments unit tests ~~~~~~~~~~~~~~~~~~ Usage:: python run.py [testfile ...] :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import sys, os if sys.version_info >= (3,): # copy test suite over ...
_run_2to3 testroot = os.path.dirname(__file__) newroot = os.path.join(testroot, '..', 'build/lib/test') copydir_run_2to3(testroot, newroot) # make nose believe that we run from the converted dir os.chdir(newroot) else: # only find tests in this directory os.chdir(os.path.dirname(__file__)) ...
e the current source is first on sys.path sys.path.insert(0, '..') import pygments except ImportError: print ('Cannot find Pygments to test: %s' % sys.exc_info()[1]) sys.exit(1) else: print ('Pygments %s test suite running (Python %s)...' % (pygments.__version__, sys.version.split()[0])) ...
synergeticsedx/deployment-wipro
openedx/core/djangoapps/cache_toolbox/relation.py
Python
agpl-3.0
3,965
0.000252
""" Caching instances via ``related_name`` -------------------------------------- ``cache_relation`` adds utility methods to a model to obtain ``related_name`` instances via the cache. Usage ~~~~~ :: from django.db import models from django.contrib.auth.models import User class Foo(models.Model): ...
m previous session) >>> foo.name = "New n
ame" >>> foo.save() # Cache is cleared on save >>> user = User.objects.get(pk=1) >>> user.foo_cache # Cache miss. <Foo: > Manual invalidation may also be performed using the following methods:: >>> user_instance.foo_cache_clear() >>> User.foo_cache_clear_fk(user_instance_pk) Manual invalidati...
indradhanush/Instamojo-Clone
clone/migrations/0002_auto__add_field_product_date_added.py
Python
gpl-3.0
4,593
0.00762
# -*- 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 field 'Product.date_added' db.add_column(u'clone_product', 'date...
elds.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [
], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), ...
jabbalaci/PrimCom
data/python/my_except.py
Python
gpl-2.0
660
0.007576
# found at http://stackoverflow.com/questions/855759/python-try-else # The statements in the else block are executed if execution falls off # the bottom of the try, i.e. if there was no exception. try: operation_that_can_throw_ioerror() except IOError: handle_the_exception_somehow() else: # we don't wan...
ure: # # * another_operation_that_can_throw_ioerror() is only run if there's no exception, # * it's run before the finally block, and # * any I
OErrors it raises aren't caught here
kobejean/tensorflow
tensorflow/contrib/distributions/python/ops/vector_student_t.py
Python
apache-2.0
10,470
0.001242
# 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...
be scalar if `loc`, `scale_*` imply non-scalar batch_shape or must have the same `batch_shape` implied by `loc`, `scale_*`. loc: Floating-point `Tensor`. If this is set to `None`, no `loc` is applied. scale_identity_multiplier: floating point rank 0 `Tensor` representing a s...
. Otherwise no scaled-identity-matrix is added to `scale`. scale_diag: Floating-point `Tensor` representing the diagonal matrix. `scale_diag` has shape [N1, N2, ..., k], which represents a k x k diagonal matrix. When `None` no diagonal term is added to `scale`. scale_tril: Floating-p...
NoMod-Programming/PyRobotC
pyRobotC.py
Python
mit
19,127
0.023997
import ast import traceback import os import sys userFunctions = {} renames = ['vex.pragma','vex.motor','vex.slaveMotors','vex.motorReversed'] classNames = [] indent = ' ' sameLineBraces = True compiled = {} def module_rename(aNode): if aNode.func.print_c() == 'vex.pragma': asC = '#pragma ' useComma =...
.format_exc()) print(ast.dump(childNode)) return asC asC += '}\n' return asC class C_arguments(ast.arguments): def prepare(self): self.minArgs = len(self.args) - len(self.defaults) self.maxArgs = len(self.args) def print_c(self): retu
rn self class C_Name(ast.Name): def prepare(self): pass def print_c(self): if self.id == 'True': return 'true' elif self.id == 'False': return 'false' elif self.id == 'None': return '0' return self.id if "NameConstant" in ast.__dict__: class C_NameConstant(ast.NameCons...
stoewer/nixpy
nixio/pycore/h5group.py
Python
bsd-3-clause
10,059
0
# Copyright (c) 2016, German Neuroinformatics Node (G-Node) # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted under the terms of the BSD License. See # LICENSE file in the root of the Project. from __future__ import (absolute_import, division, ...
ame] except
Exception: raise ValueError("Error deleting {} from {}".format(name, self.name)) # Delete if empty and non-root container groupdepth = len(self.group.name.split("/")) - 1 if not len(self.group) and groupdepth > 1: ...
abahdanovich/distorm
disOps/disOps.py
Python
gpl-3.0
22,792
0.031985
# # disOps.py v 1.0.0 # # Copyright (C) 2011 Gil Dabah, http://ragestorm.net/disops/ # # disOps is a part of the diStorm project, but can be used for anything. # The generated output is tightly coupled with diStorm data structures which can be found at instructions.h. # The code in diStorm that actually walks th...
l defined instructions in x86defs.c mnemonicsIds = {} # mnemonic : offset to mnemonics table of strings. idsCounter = len("undefined") + 2 # Starts immediately after this one. # Support SSE pseudo compare instructions. We wil
l have to add them manually. def FixPseudo(mnems): return [mnems[0] + i + mnems[1] for i in ["EQ", "LT", "LE", "UNORD", "NEQ", "NLT", "NLE", "ORD"]] # Support AVX pseudo compare instructions. We will have to add them manually. def FixPseudo2(mnems): return [mnems[0] + i + mnems[1] for i in ["EQ", "LT", "LE", ...
secgroup/MTFGatheRing
code/web.py
Python
mit
7,006
0.007708
#!/usr/bin/env python3 import time import random import socket from flask import Flask, render_template, redirect, url_for, request, jsonify import config log = None # classes class Agent(): def __init__(self, ip, cw=True, node=None, state='initial'): self.ip = ip self.cw = cw self.state...
s) log.write('[Status pre]\n') log.write(str(app.ring.dump())) agent = app.agents[agent_ip] agent.state = state agent.cw = agent.cw if not turned else not agent.cw blocked = app.ring.blocked(agent) if not blocked and not stopped: # advance to the next node if not blocked ...
(agent_ip) log.write('\n[Status post]\n') log.write(str(app.ring.dump())) return jsonify(blocked=blocked) @app.route('/') def index(): return render_template('base.html', started=app.started) def main(): app.run(host='0.0.0.0', debug=config.debug) if __name__ == '__main__': main()
makinacorpus/ionyweb
ionyweb/plugin_app/plugin_video/admin.py
Python
bsd-3-clause
157
0
# -*- coding: utf-8 -*- from django.contrib import admin from ionyw
eb.plugin_app.plugin_video.models impo
rt Plugin_Video admin.site.register(Plugin_Video)
opticode/eve
eve/auth.py
Python
bsd-3-clause
9,706
0.000103
from flask import request, Response, current_app as app, g, abort from functools import wraps def requires_auth(endpoint_class): """ Enables Authorization logic for decorated functions. :param endpoint_class: the 'class' to which the decorated endpoint belongs to. Can be 'resource...
resource['allowed_item_roles'] if request.method in ['GET', 'HEAD', 'OPTIONS']: roles += resource['allowed_item_read_roles'] else: roles += resource['allowed_item_write_roles'] if callable(resource['authentication']...
tion']() else: auth = resource['authentication'] else: # home resource_name = resource = None public = app.config['PUBLIC_METHODS'] + ['OPTIONS'] roles = app.config['ALLOWED_ROLES'] if request...
androomerrill/scikit-nano
sknano/structures/tests/test_graphene.py
Python
bsd-2-clause
1,925
0
# -*- coding: utf-8 -*- # from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import nose from nose.tools import * import numpy as np from sknano.structures import Graphene, PrimitiveCellGraphene, \ ConventionalCellGraphene, GraphenePrimitiveCell, GrapheneConv...
_length=5, zigzag_edge_length=5) assert_equals(s.zigzag_edge_length, 5) assert_equals(s.armchair_edge_length, 5) assert_true(isinstance(s, ConventionalCellGraphene)) assert_true(isinstance(s.unit_cell, GrapheneConventionalCell)) print(s.unit_cell) def test2(): s = PrimitiveCellGraphene(edge_le...
, PrimitiveCellGraphene)) assert_true(isinstance(s.unit_cell, GraphenePrimitiveCell)) print(np.degrees(s.r1.angle(s.r2))) print(s.unit_cell) print(s.area) print(s) def test3(): s = ConventionalCellGraphene(armchair_edge_length=5, zigzag_edge_length=5) assert_equals(s.zigzag_edge_length, 5)...
jumpifzero/morango
modelparser.py
Python
mit
5,062
0.01857
# ============================================================ # modelparser.py # # (C) Tiago Almeida 2016 # # Still in early development stages. # # This module uses PLY (http://www.dabeaz.com/ply/ply.html) # and a set of grammar rules to parse a custom model # definition language. # =======================...
no += len(t.value) # A string containing ignored characters (spaces and tabs) t_ignore = ' \t' # Error handling rule def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) # ====================================================
======== # Parser rules # ============================================================ # ---------------- # BNF Grammar # ---------------- # model : MODELNAME { fields } # fields : fields field ; # | field ; models = [] fields = [] def p_file(p): """ rules : models """ p[0] = p[1] ...
rishabhsixfeet/Dock-
MessagesApp/models.py
Python
mit
1,894
0.015312
from django.db import models from django.contrib.auth.models import User from helper_functions import my_strftime # Create your models here. #This only contains metadata about this thread (i.e. just the subject for now) #It is used in a Many-to-Many relationship with User, with a through object that contains the has_...
s most recent message/author, title, etc. """ if user == None: has_been_read = False else: has_been_
read = ThreadMembership.objects.get(user=user, thread=self).has_been_read last_message = self.message_set.order_by('-time_sent')[0] return { 'subject' : self.subject, 'last_message' : last_message.getDetail(), 'id' : self.id, 'has_been_read' : has_been_read } class Message(models.Mode...
aksareen/balrog
auslib/test/admin/views/test_permissions.py
Python
mpl-2.0
45,228
0.004533
import mock import simplejson as json from auslib.global_state import dbo from auslib.test.admin.views.base import ViewTest class TestUsersAPI_JSON(ViewTest): def testUsers(self): ret = self._get('/users') self.assertEqual(ret.status_code, 200) data = json.loads(ret.data) data['u...
qual(data, dict(users=set(['bill', 'billy', 'bob', 'ashanti', 'mary', 'julie']))) class TestCurrentUserAPI_JSON(ViewTest): def testGetCurrentUser(self): ret = self._get("/users/current", use
rname="bill") self.assertEqual(ret.status_code, 200) data = json.loads(ret.data) expected = { "username": "bill", "permissions": { "admin": { "options": None, "data_version": 1, }, }, "roles": { ...
UKPLab/deeplearning4nlp-tutorial
2017-07_Seminar/Session 4 - LSTM Sequence Classification/code/preprocess.py
Python
apache-2.0
6,664
0.012905
""" The file preprocesses the files/train.txt and files/test.txt files. I requires the dependency based embeddings by Levy et al.. Download them from his website and change the embeddingsPath variable in the script to point to the unzipped deps.words file. """ from __future__ import print_function import numpy as np ...
hape: ", wordEmbeddings.shape) print("Len words: ", len(words)) embeddings = {'wordEmbeddings': wordEmbeddings, 'word2Idx': word2Idx, 'caseEmbeddings': caseEmbeddings, 'case2Idx': case2Idx, 'label2Idx': label2Idx} f = gzip.open(embeddingsPklPath, 'wb') pkl.dump(embeddings, f, -1) f.close(
) # :: Create matrices :: train_set = createMatrices(trainSentences, window_size, word2Idx, label2Idx, case2Idx) dev_set = createMatrices(devSentences, window_size, word2Idx, label2Idx, case2Idx) test_set = createMatrices(testSentences, window_size, word2Idx, label2Idx, case2Idx) f = gzip.open(outputFilePath, 'wb'...
vigetlabs/dnsimple
tests/unit/test_client.py
Python
mit
3,371
0.019875
import pytest from ..context import dnsimple, fixture_path from ..request_helper import RequestHelper, request from dnsimple.client import Client class TestClient(RequestHelper, object): def test_constructor_raises_errors_when_improperly_configured(self): with pytest.raises(dnsimple.credentials....
': 1}) subject.request = request result = subject.transfer('foo.com', contact) method.assert_called_once_with('domain_transfers', {'domain': {'name': 'foo.com', 'registrant_id': 1}}) assert result == True def test_transfer_returns_false_when_transfer_fails(self, mocker, request)...
subject = Client(email = 'user@host.com', password = 'password') contact = dnsimple.models.Contact(request, {'id': 1}) subject.request = request result = subject.transfer('foo.com', contact) assert result == False
esten/StoriTell
StoriTell/stories/api.py
Python
bsd-3-clause
583
0.015437
from storitell.tastypie.resources import ModelResource from storitell.stories.models import Story from storitell.stories.extra_methods import moderate_comment from storitell.tastypie.validation import Validation # Stories can be read through a REST-ful inter
face. It'd be nice # to be able to POST as well, but t
hat requires validation I haven't # had time to code yet. Want to add it? Be my guest. class StoryResource(ModelResource): class Meta: queryset = Story.objects.all() resource_name = 'story' fields = ['maintext','pub_date','upvotes'] allowed_methods = ['get']
tstenner/bleachbit
tests/TestWinapp.py
Python
gpl-3.0
19,272
0.00109
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.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 License, or # ...
def run_all(self, cleaner, really_delete): """Test all the cleaner options""" for (option_id, __name) in cleaner.get_options(): for cmd in cleaner.get_commands(option_id): for result in cmd.execute(really_delete):
common.validate_result(self, result, really_delete) @common.skipUnlessWindows def test_remote(self): """Test with downloaded file""" winapps = Winapp(get_winapp2()) for cleaner in winapps.get_cleaners(): self.run_all(cleaner, False) def test_detectos(self): ...
drogenlied/qudi
core/base.py
Python
gpl-3.0
10,150
0.001872
# -*- coding: utf-8 -*- """ This file contains the Qudi module base class. Qudi 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. Qudi is dis...
s * Get your own configuration (for save) * Get name of status variables * Get status variables * Reload module data (from saved variables) """ sigStateChanged = QtCore.Signal(object) # (module name,
state change) _modclass = 'base' _modtype = 'base' _in = dict() _out = dict() def __init__(self, manager, name, config=None, callbacks=None, **kwargs): """ Initialise Base class object and set up its state machine. @param object self: tthe object being initialised @par...
blond-admin/BLonD
blond/toolbox/parameter_scaling.py
Python
gpl-3.0
21,008
0.004665
# coding: utf8 # Copyright 2014-2020 CERN. This software is distributed under the # terms of the GNU General Public Licence version 3 (GPL Version 3), # copied verbatim in the file LICENCE.md. # In applying this licence, CERN does not waive the privileges and immunities # granted to it by virtue of its status as...
e(self): self.eta_0 = np.fabs(1./self.gamma_t**2 - 1./self.gamma**2) self.tb1.append(" Slippage factor (zeroth order): "+ np.str(self.eta_0)+"") self.Q_s0 = np.sqrt(self.harmonic*self.voltage*self.eta_0 /
(2.*np.pi*self.beta_sq*self.energy)) self.tb1.append(" Central synchrotron tune: "+np.str(self.Q_s0)+"") self.f_s0 = self.Q_s0*self.f_rev self.tb1.append(" Central synchrotron frequency: "+ np.str(self.f_s0)+"") self.omega_s0 = 2.*np.pi*self....
joachimmetz/plaso
plaso/parsers/aws_elb_access.py
Python
apache-2.0
14,893
0.00235
# -*- coding: utf-8 -*- """Parser for AWS ELB access logs. This parser is based on the log format documented at https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html Note: The AWS documentation is not clear about the meaning of the "target_port_list" field. The assumption ...
nations that processed this request. destination_status_code_list (str): A space-delimited list of status codes
. classification (str): The classification for desync mitigation. classification_reason (str): The classification reason code. """ DATA_TYPE = 'aws:elb:access' def __init__(self): """Initializes event data.""" super(AWSELBEventData, self).__init__(data_type=self.DATA_TYPE) self.request_type ...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractStealtranslationHomeBlog.py
Python
bsd-3-clause
108
0.055556
def
extractStealtranslationHomeBlog(item): ''' Parser fo
r 'stealtranslation.home.blog' ''' return None
robotpilot/robomongo
src/third-party/mongodb/buildscripts/bcp.py
Python
gpl-3.0
824
0.053398
import utils import os import shutil import sys def go( boost_root ): OUTPUT = "src/third_party/boost" if os.path.exists( OUTPUT ): shutil.rmtree( OUTPUT ) cmd = [ "bcp" , "--scan" , "--boost=%s" % boost_root ] src = utils.getAllSourceFiles() cmd += src cmd.append( OUTP...
PUT ) res = utils.execsys( cmd ) out = open( OUTPUT + "/bcp-out.txt" , 'w' ) out.write( re
s[0] ) out.close() out = open( OUTPUT + "/notes.txt" , 'w' ) out.write( "command: " + " ".join( cmd ) ) out.close() print( res[1] ) if __name__ == "__main__": if len(sys.argv) == 1: print( "usage: python %s <boost root directory>" % sys.argv[0] ) sys.exit(1) go( sys.ar...
botlabio/autonomio
autonomio/save_model_as.py
Python
mit
1,376
0.001453
def save_model_as(X, columns, model, save_model, flatten): '''Model Saver WHAT: Saves a trained model so it can be loaded later for predictions by predictor(). ''' model_json = model.to_json() with open(save_model+".json", "w") as json_file: json_file.write(model_json) model.save...
for i in X: temp += i+" " temp = temp[:-1] # for an integer as column name (int) if type(X) == int: temp = columns[X] # for a single column label which contains string values if type(X) == str: temp = X temp += " "+str(flatten) f.w
rite(temp) f.close()
PaulaEstrella/MTTT-PyQT
MTTTCore.py
Python
gpl-3.0
15,580
0.005969
"""@brief MTTT's core commands, stems from the original version created using Gtk https://github.com/roxana-lafuente/MTTT""" # !/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # # Machine Translation Training Tool # Copyright (C) 2016 Roxan...
en the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURP
OSE. 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.org/licenses/>. # ############################################################################## def install_and_import(package): ...
openrobotics/openrobotics_thunderbot
pyttsx/pyttsx/driver.py
Python
mit
6,982
0.000573
''' Proxy for drivers. Copyright (c) 2009, 2013 Peter Parente Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR ...
= self._queue[0] except IndexError: break if(mtd == self._engine.endLoop): break self._queue.p
op(0) self._driver.stop() def getProperty(self, name): ''' Called by the engine to get a driver property value. @param name: Name of the property @type name: str @return: Property value @rtype: object ''' return self._driver.getProperty(name)...
nkrinner/nova
nova/api/openstack/compute/servers.py
Python
apache-2.0
61,851
0.00042
# Copyright 2010 OpenStack Foundation # Copyright 2011 Piston Cloud Computing, 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.apach...
ts metadata_node = self.find_first_child_named(s
erver_node, "metadata") if metadata_node is not None: server["metadata"] = self.extract_metadata(metadata_node) user_data_node = self.find_first_child_named(server_node, "user_data") if user_data_node is not None: server["user_data"] = self.extract_text(user_data_node) ...
nttks/edx-platform
lms/envs/acceptance.py
Python
agpl-3.0
6,447
0.002482
""" This config file extends the test environment configuration so that we can run the lettuce acceptance tests. """ # We intentionally define lots of variables that aren't used, and # want to import all variables from base settings files # pylint: disable=wildcard-import, unused-wildcard-import from .test import * f...
s and logging them in FEATURE
S['AUTOMATIC_AUTH_FOR_TESTING'] = True # Enable third-party authentication FEATURES['ENABLE_THIRD_PARTY_AUTH'] = True THIRD_PARTY_AUTH = { "Google": { "SOCIAL_AUTH_GOOGLE_OAUTH2_KEY": "test", "SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET": "test" }, "Facebook": { "SOCIAL_AUTH_FACEBOOK_KEY": "te...
DLR-SC/DataFinder
src/datafinder/gui/admin/datastore_configuration_wizard/gridftp/__init__.py
Python
bsd-3-clause
1,999
0.018009
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # # Copyright (c) 2003-2011, German Aerospace Center (DLR) # All rights reserved. # #Redistribution and use in source and binary forms, with or without # #modification, are permitted provided that the following conditions are #met: # ...
NOT #LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #OF THIS SOFTWARE, EVEN...
om datafinder.gui.admin.datastore_configuration_wizard.gridftp import performance_option_controller from datafinder.gui.admin.datastore_configuration_wizard.gridftp import security_option_controller __version__ = "$Revision-Id:$"
boos/cppcheck
addons/test/util.py
Python
gpl-3.0
1,250
0.0008
# Helpers for pytest tests import subprocess import json import os def find_cppcheck_binary(): possible_locations = [ "./cppcheck", "./build/bin/cppcheck", r".\bin\cppcheck.exe", ] for location in possible_locations: if os.path.exists(location): break else: ...
.Popen(["rm", "-f", fpath + ".dump"]) def convert_json_output(raw_json_strings): """Convert raw stdout/stderr cppcheck JSON output to python dict.""" json_output = {} for line in raw_json_st
rings: try: json_line = json.loads(line) # json_output[json_line['errorId']] = json_line json_output.setdefault(json_line['errorId'], []).append(json_line) except ValueError: pass return json_output
dhosterman/hebrew_order_david
accounts/admin.py
Python
mit
1,111
0.0018
from django.contrib import admin from .models import User from application.models import (Contact, Personal, Wife, Occupation, Children, Hod, Committee, UserCommittee, Legal) # Register your models here. class ContactInline(admin.StackedInline): model = Contact class PersonalInli...
kedInline): model = Occupation class HodInline(admin.StackedInline): model = Hod class ChildrenInline(admin.StackedInline): model = Children class UserCommitteeInline(admin.StackedInline): model = UserCommittee class UserAdmin(admin.ModelAdmin): inlines = [ ContactInline, Per...
(admin.ModelAdmin): model = Legal admin.site.register(User, UserAdmin) admin.site.register(Legal, LegalAdmin) admin.site.site_header = 'Hebrew Order of David Administration'
pmghalvorsen/gramps_branch
gramps/gen/utils/string.py
Python
gpl-2.0
3,058
0.014716
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2009 Gary Burton # Copyright (C) 2011 Tim G L Lyons # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published ...
y 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ String mappings for constants """ #-------------------------------------------------------------------------...
DedMemez/ODS-August-2017
safezone/DistributedFindFour.py
Python
apache-2.0
35,125
0.001964
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.safezone.DistributedFindFour from panda3d.core import BitMask32, CollideMask, CollisionHandler, CollisionHandlerQueue, CollisionNode, CollisionRay, CollisionSphere, CollisionTube, Lens, NodePath, TextNode, Vec3, Vec4 from direct.distributed.ClockDelt...
ButtonPushed()
def setTableDoId(self, doId): self.tableDoId = doId self.table = self.cr.doId2do[doId] self.table.setTimerFunc(self.startButtonPushed) self.fsm.enterInitialState() self.table.setGameDoId(self.doId) def disable(self): DistributedNode.DistributedNode.disab...
yw374cornell/e-mission-server
emission/storage/timeseries/format_hacks/move_filter_field.py
Python
bsd-3-clause
2,215
0.006321
# For some reason, probably because we were trying to serialize the default # object, we put the "filter" field into the metadata. But the filter doesn't # make sense for data other than location, so it doesn't seem like it should be # in the metadata. Putting it into the metadata also means that it is not # accessible...
, found key %s, moved filter %s into data" % (entry["_id"], get_curr_key(entry), curr_filter)) # For all cases, including the location one, we want to delete t
he filter from metadata del entry["metadata"]["filter"] tsdb.save(entry) logging.debug("for entry %s, for key %s, deleted filter %s from metadata" % (entry["_id"], get_curr_key(entry), curr_filter)) else: pass # logging.war...
OSSESAC/odoopubarquiluz
addons/document_page/wizard/document_page_create_menu.py
Python
agpl-3.0
3,491
0.002292
# -*- 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...
# only the super user is allowed to create menu due to security rules on ir.values menu_id = obj_menu.create(cr, SUPERUSER_ID, { 'name': data.menu_name, 'parent_id':data.menu_parent_id.id, 'icon': 'STOCK_DIALOG_QUESTION', ...
n_id), }, context) obj_page.write(cr, uid, [page_id], {'menu_id':menu_id}) return { 'type': 'ir.actions.client', 'tag': 'reload', } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
pdevetto/super-duper-disco
movies/models.py
Python
gpl-3.0
1,963
0.027509
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible DIRECTOR = 0 ACTOR = 1 PRODUCER = 2 SCREENPLAY = 3 PHOTOGRAPHY = 4 WRITER = 5 PEOPLE_ROLE = ( (DIRECTOR, 'Director'), (ACTOR, 'Actor'), (PRODUCER, 'Producer'), (SCREENPLAY, 'Sc...
tmdb_id = models.IntegerField(blank=True) def __str__(self): return self.name @python_2_unicode_compatible class Movie(models.Model): title = models.CharField(max_length=200, blank=True) titlehash = mode
ls.CharField(max_length=200) filename = models.CharField(max_length=200, blank=True) filepath = models.CharField(max_length=255, blank=True) poster = models.CharField(max_length=200, null=True) year = models.IntegerField(null=True) tmdb_id = models.IntegerField(null=True) clean ...
philippbosch/django-geoposition
geoposition/apps.py
Python
mit
129
0.007752
from django.apps i
mport AppConfig class GeoPositionConfig(AppConfig): name = 'geoposition' v
erbose_name = "GeoPosition"
robmcmullen/atrcopy
atrcopy/dcm.py
Python
gpl-2.0
1,753
0.001711
import numpy as np from . import errors from .container import DiskImageContainer from .segments import SegmentData class DCMContainer(DiskImageContainer): valid_densities = { 0: (720, 128), 1: (720, 256), 2: (1040, 128), } def get_next(self): try: data = self...
= 0xf9 or archive_type == 0xfa: archive_flags = self.get_next() if archive_flags & 0x1f != 1: if archive_type == 0xf9: raise errors.InvalidContainer("DCM m
ulti-file archive combined in the wrong order") else: raise errors.InvalidContainer("Expected pass one of DCM archive first") density_flag = (archive_flags >> 5) & 3 if density_flag not in self.valid_densities: raise errors.InvalidContainer(f"U...
mbiciunas/nix
test/cli_config/tag/test_tag_show.py
Python
gpl-3.0
1,291
0.001549
import pytest from cli_config.tag import tag from utility.nix_error import NixError def test_tag_show_no_tag(capsys): with pytest.raises(SystemExit) as _excinfo: tag.tag("nixconfig", ["show"]) _out, _err = capsys.readouterr() assert "2" in str(
_excinfo.value), "Exception doesn't contain expected string" assert len(_out) == 0, "StdOut should be empty, contains: {}".format(_out) assert "the following arguments are required: tag" in _err, "StdErr doesn't contain expected string" def test_tag_show_invalid_tag(capsys): with pytest.raises(NixError) a...
tag.tag("nixconfig", ["show", "badtag"]) _out, _err = capsys.readouterr() assert "Unknown tag: badtag" in str(_excinfo.value) assert len(_out) == 0, "StdOut should be empty, contains: {}".format(_out) assert len(_err) is 0, "StdErr should be empty, contains: {}".format(_err) def test_tag_show_good_t...
mapledyne/skytap
skytap/models/Interface.py
Python
mit
1,497
0
"""Support for an interface resource in Skytap.""" import json from skytap.framework.ApiClient import ApiClient # noqa from skytap.models.PublishedServices import PublishedServices # noqa from skytap.models.SkytapResource import SkytapResource # noqa class Interface(SkytapResource): """One Skytap (network) In...
rmation on demand. This allows saving of API calls (we don't request this unless you're accessing Published Services), but also you can treat the object as if the services are there all along. We'll get the info when you ask for it, and you can move along like it was there from the start...
= 'services': api = ApiClient() services_json = json.loads(api.rest(self.url)) self.services = PublishedServices(services_json["services"], self.url) return self.services return super(Interface, self).__getattr__(key)...
UnrememberMe/pants
contrib/codeanalysis/src/python/pants/contrib/codeanalysis/tasks/index_java.py
Python
apache-2.0
3,430
0.010496
# coding=utf-8 # Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pant...
er_cp))] jvm_options.extend(self.get_options().jvm_options) for vt in invalidation_check.invalid_vts: self._index(vt, indexer_cp, jvm_options) for vt in invalidation_check.all_vts:
entries = self._entries_file(vt) self.context.products.get_data('kythe_entries_files', dict)[vt.target] = entries def _index(self, vt, indexer_cp, jvm_options): self.context.log.info('Kythe indexing {}'.format(vt.target.address.spec)) kindex_file = self.context.products.get_data('kindex_files').get(vt...
AC130USpectre/Python-programs
ModuleOperators.py
Python
gpl-3.0
1,078
0.004638
#some useful operations in module arithmetic def power2(base, mod): return (base ** 2) % mod def prod(num1, num2, mod): return (num1 * num2) % mod def power(base, exp, mod)
: k = 0 while exp >> k != 0: k
+= 1 k -= 1 result = base for i in range(k - 1, -1, -1): if 1 << i & exp == 0: result = power2(result, mod) else: result = prod(power2(result, mod), base, mod) return result def euclid(a, b): if a % b == 0: return b else: ret...
Glottotopia/aagd
moin/local/moin/build/lib.linux-x86_64-2.6/MoinMoin/script/cli/show.py
Python
mit
723
0.002766
# -*- coding: iso-8859-1 -*- """ MoinMoin - cli show script @copyright: 2006 MoinMoin:ThomasWaldmann @license: GNU GPL, see COPYING for details. """ from MoinMoin.script import MoinScript from MoinMoin.wsgiapp import run class PluginScript(MoinScript): """\ Purpose: ======== Just run a CLI request...
--config-dir=/path/to/my/cfg/ --wiki-url=http://wiki.example.org/ """ def __init__(self, argv, def_values): MoinScript.__init__(self,
argv, def_values) def mainloop(self): self.init_request() run(self.request)
bdaroz/the-blue-alliance
tests/test_key_name_validators.py
Python
mit
2,185
0.003204
import unittest2 from models.event import Event from models.match import Match from models.team import Team class TestKeyNameValidators(unittest2.TestCase): def setUp(self): self.valid_team_key = "frc177" self.valid_team_key2 = "frc1" self.invalid_team_key = "bcr077" self.invalid_...
y2), True) def test_invalid_team_key(self): self.assertEqual(Team.validate_key_name(self.invalid_team_key), False) self.assertEqual(Team.validate_key_name(self.invalid_team_key2), False) self.assertEqual(Team.validate_key_name(self.invalid_team_key3), False) def test_valid_event_key(se...
self.assertEqual(Event.validate_key_name(self.valid_event_key2), True) def test_invalid_event_key(self): self.assertEqual(Event.validate_key_name(self.invalid_event_key), False) self.assertEqual(Event.validate_key_name(self.invalid_event_key2), False) self.assertEqual(Event.validate_key_nam...
UCHIC/WaterMonitor
Current_Designs/Computational_Datalogger/Software/template.py
Python
bsd-3-clause
1,582
0.006953
import Logger import os # The following five lines of code MUST ABSOLUTELY appear in this order. DO NOT MOVE OR CHANGE THE FOLLOWING FOUR LINES OF CODE. # Logger.initPins() Should never be called by the user. It should only be called when this script is automatically run. Logger.init() # Initialzie the Logger Pytho...
pberry Pi is powered on dataTuple = Logger.loadData() # Read the data from the EEPROM chip Logger.setRomFree() # Tell the AVR datalogger that the EEPROM chip is no longer in use. # Process the contents of dataTuple here. The format is as follows: # Index | dataTuple # -------------------------------------------...
Day logging started # 4 Hour logging started # 5 Minute logging started # 6 Second logging started # 7 Data Byte # 8 Data Byte # 9 Data Byte # 10 Data Byte # ... ... if (dataTuple[0] == Logger.bufferMax()): # This means that the Pi was turned on b...
samuelgarcia/python-neo
neo/io/plexonio.py
Python
bsd-3-clause
594
0
from neo.io.basefromrawio import B
aseFromRaw from neo.rawio.plexonrawio import PlexonRawIO class PlexonIO(PlexonRawIO, BaseFromRaw): """ Class for reading the old data format from Plexon acquisition system (.plx) Note that Plexon now use a new format PL2 which is NOT supported by this IO. Compatible with versions 100 to 106....
PlexonRawIO.__init__(self, filename=filename) BaseFromRaw.__init__(self, filename)
Rignak/Scripts-Python
Servlet/readme_maker.py
Python
gpl-3.0
1,062
0.000942
# -*- coding: utf-8 -*- """ Created on Tue Apr 9 21:30:31 2019 @author: Rignak """ import os from os.path import join, split lines = [] for root, folders, filenames in os.walk('..'): for filename in filenames: if filename == 'readme.md': lines += [''] with open(join(root, filena...
[-1][:-1] line = line.replace(path, root[3:] + '/' + path) lines.append(line) lines.append("\n</details>\n") with open(j
oin('..', 'README.md'), 'w', encoding='utf-8') as file: for line in lines: file.write(line)
karlalopez/hackbright
objects-tom/solution/objects4.py
Python
apache-2.0
344
0.008721
class Student(object):
"""For student records""" def __init__(self, name=None): # This special method is called a "constructor" self.name = name def print_name(self): print self.name jenny = Student('Jenny'
) jenny.print_name() # prints 'Jenny' ### Exercise Time ### bill = Student() bill.print_name()
lino-framework/lino
lino/core/ddh.py
Python
bsd-2-clause
3,228
0.00031
# -*- coding: UTF-8 -*- # Copyright 2009-2018 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) """Defines the :class:`DisableDeleteHandler` class. See :doc:`/dev/delete`. """ # import logging ; logger = logging.getLogger(__name__) from django.conf import settings from dj...
rom kernel during startup. fk_model is None for # fields defined on a parent model. for m, fld in self.fklist: if model is m and fld.name == fk.name: # avoid duplicate entries caused by MTI children return self.fklist.append((model, fk)) def ...
,'.join([m.__name__ + '.' + fk.name for m, fk in self.fklist]) return "<DisableDeleteHandler(%s, %s)>" % (self.model, s) def disable_delete_on_object(self, obj, ignore_models=set()): """Return a veto message which explains why this object cannot be deleted. Return `None` if there is no vet...
monumentum/mongoenginerics
mongoenginerics/adapter/apistar.py
Python
mit
1,346
0
import importlib import json from .base import MongoEnginericsAdapter class ApistarWSGIAdapter(MongoEnginericsAdapter): def __init__(self, *arg
s, **kwargs): self.engine = importlib.import_module('apistar') self._wsgi = importlib.import_module('apistar.frameworks.wsgi') super(ApistarWSGIAdapter, self).__init__(*args, **kwargs) def attach(self, ctrl): def find(query: self.engine.http.QueryParams): return ctrl.fin...
ine.http.Body): return ctrl.update(item_id, json.loads(updates)) def create(body: self.engine.http.Body): return ctrl.create(json.loads(body)) def find_one(item_id): return ctrl.find_one(item_id) def delete(item_id): return ctrl.delete(item_id) ...
Jakeable/Ralybot
plugins/steamdb.py
Python
gpl-3.0
3,386
0.003839
import re import requests import bs4 from ralybot import hook from ralybot.util import web # different forks of cloudflare-scrape have different package layouts try: from cfscrape import cfscrape except ImportError: import cfscrape except ImportError: cfscrape = None class SteamError(Exception): pa...
ts.exceptions.ConnectionError) as e: raise SteamError("Could not get user info: {}".format(e)) # parse that page! soup = bs4.BeautifulSoup(request.content) # get all the data we need try: data["name"] = soup.find("h1", {"class": "header-title"}).find("a").text data["url"] = req...
ta["value_sales"] = soup.find("h1", {"class": "calculator-price-lowest"}).text data["count"] = int(soup.find("div", {"class": "pull-right price-container"}).find("p").find("span", {"class": ...
Lenchik13/Testing
fixture/application.py
Python
apache-2.0
1,000
0.001
from selenium import webdriver from fixture.session import SessionHelper from fixture.group import GroupHelper from fixture.contact import ContactHelper class Application: def __init__(self, browser, base_url): if browser == "firefox": self.wd = webdriver.Firefox() elif browser == "ch...
wd = webdriver.Ie() else: raise ValueError("Unrecognezed browser %s" % browser) self.session = SessionHelper(self) self.group = GroupHelper(self) self.contact = ContactHelper(self) self.base_url = base_url def is_valid(self): try: self.wd.curr
ent_url return True except: return False def open_home_page(self): wd = self.wd if not (wd.current_url.endswith("/addressbook/")): wd.get(self.base_url) def destroy(self): self.wd.quit()
Shuailong/Leetcode
solutions/nim-game.py
Python
mit
920
0.007609
#!/usr/bin/env python # encoding: utf-8 """ nim-game.py Created by Shuailong on 2015-12-21. https://leetcode.com/problems/nim-game/. """ class Solution1(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ '''Too time consuming''' win1 = True ...
r not win3 win1 = win2 win2 = win3 win
3 = win i += 1 return win class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ '''Find the law and rewrite''' return n & 3 != 0 # return n % 4 != 0 def main(): solution = Solution() n = 4 print ...
gojira/tensorflow
tensorflow/contrib/tpu/profiler/pip_package/setup.py
Python
apache-2.0
2,551
0
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
or='Google Inc.', author_email='opensource@google.com', packages=['cloud_tpu_profiler'], package_data={ 'cloud_tpu_profiler': ['data/*'], }, entry_points={ 'console_scripts': CONSOLE_SCRIPTS, }, classifiers=[ # How mature i
s this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: ...
ds-hwang/deeplearning_udacity
python_practice/quiz1.py
Python
mit
409
0.007335
"""Softmax.""" scores = [3.0, 1.0, 0.2] import numpy as np def softmax(x): "
""Compute softmax values for each sets of scores in x.""" return np.exp(x) / sum(np.exp(x)) print(softmax(scores)) # Plot softmax curves import matplotlib.pyplot as plt x = np.arange(-2.0, 6.0, 0.1) scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)]) plt.plot(x, soft
max(scores).T, linewidth=2) plt.show()
jerrrytan/bitcamp
bitcamp/manage.py
Python
mit
250
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.set
default("DJANGO_SETTINGS_MODULE", "bitcamp.settings") from django.core.managemen
t import execute_from_command_line execute_from_command_line(sys.argv)
StefanRijnhart/stock-logistics-warehouse
stock_reserve/model/stock_reserve.py
Python
agpl-3.0
6,546
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2013 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
"" domain = [('date_validity', '<', fields.date.today()), ('state', '=', 'assigned')] if ids: domain.append(('id', 'in', ids)) reserv_ids = self.search(domain) reserv_ids.release() return True @api.multi def unlink(self): """ Release...
nge_product_id(self): """ set product_uom and name from product onchange """ # save value before reading of self.move_id as this last one erase # product_id value product = self.product_id # WARNING this gettattr erase self.product_id move = self.move_id result = ...
zhangxujinsh/keras
keras/callbacks.py
Python
mit
8,643
0.00162
from __future__ import absolute_import from __future__ import print_function import theano import theano.tensor as T import numpy as np import time, json, warnings from collections import deque from .utils.generic_utils import Progbar class CallbackList(object): def __init__(self, callbacks=[], queue_length=10...
rams['verbose'] def on_epoch_begin(self, epoch, logs={}): if self.verbose: print('Epoch %d' % epoch) self.progbar = Progbar(target=self.params['nb_sample'], verbose=self.verbose) self.seen = 0 self.totals = {} def on_batch_begi...
def on_batch_end(self, batch, logs={}): batch_size = logs.get('size', 0) self.seen += batch_size for k, v in logs.items(): if k in self.totals: self.totals[k] += v * batch_size else: self.totals[k] = v * batch_size for k in sel...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.2/Lib/test/test_types.py
Python
mit
14,942
0.025833
# Python test set -- part 6, built-in types from test_support import * print '6. Built-in types' print '6.1 Truth value testing' if None: raise TestFailed, 'None is true instead of false' if 0: raise TestFailed, '0 is true instead of false' if 0L: raise TestFailed, '0L is true instead of false' if 0.0: raise TestFai...
if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))' if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation' if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3' if 0*(1,2,3) != (
): raise TestFailed, 'tuple repetition 0*' if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple' if 0 in (0,1,2) and 1 in (0,1,2) and 2 in (0,1,2) and 3 not in (0,1,2): pass else: raise TestFailed, 'in/not in tuple' print '6.5.3 Lists' if len([]) != 0: raise TestFailed, 'len([])' if len([1,]) != 1: ...
lino-framework/book
lino_book/projects/eric/tests/test_notify.py
Python
bsd-2-clause
5,765
0.002951
# -*- coding: utf-8 -*- # Copyright 2016-2017 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """Runs some tests about the notification framework. You can run only these tests by issuing:: $ go team $ python manage.py test tests.test_notify Or:: $ go noi $ python setup.py test -s tests.Project...
= create( User, username='aline', first_name="Aline", email="aline@example.com", language='fr') o
bj = create( Ticket, summary="Save the world, après moi le déluge", user=robin) create(Vote, votable=obj, user=aline) self.assertEqual(Message.objects.count(), 0) url = "/api/comments/CommentsByRFC" post_data = dict() post_data[constants....
googleapis/python-access-approval
google/cloud/accessapproval_v1/services/access_approval/__init__.py
Python
apache-2.0
769
0
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with t
he License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,
software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from .client import AccessApprovalClient from .async_client imp...
CanonicalLtd/subiquity
subiquitycore/async_helpers.py
Python
agpl-3.0
2,411
0
# Copyright 2019 Canonical, Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distribute...
THOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public Lice
nse for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import asyncio import concurrent.futures import logging log = logging.getLogger("subiquitycore.async_helpers") def _done(fut): try: ...
ros2/launch
launch_testing/launch_testing/loader.py
Python
apache-2.0
12,234
0.002779
# Copyright 2019 Apex.AI, 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 agreed to in writing...
s self.name Injected Arguments can be accessed as an argument if the test has an argument with a matching name """ # Inject test attributes into the test as self.wha
tever. This method of giving # objects to the test is pretty inferior to injecting them as arguments to the # test methods - we may deprecate this in favor of everything being an argument for name, value in injected_attributes.items(): _give_attribute_to_tests(value, name, tests) ...
nelango/ViralityAnalysis
model/lib/nltk/corpus/reader/api.py
Python
mit
17,836
0.001682
# Natural Language Toolkit: API for Corpus Readers # # Copyright (C) 2001-2015 NLTK Project # Author: Steven Bird <stevenbird1@gmail.com> # Edward Loper <edloper@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ API for corpus readers. """ from __future__ import unicode_litera...
g[file_id]`` is the encoding name for the file whose identifier is ``file_id``. If ``file_id`` is not in ``encoding``, then the file contents will be processed using non-unicode byte strings. - A list: ``encoding`` should be a list of ``(regexp, encoding)`` ...
` matches the ``file_id``. If no tuple's ``regexp`` matches the ``file_id``, the file contents will be processed using non-unicode byte strings. - None: the file contents of all files will be processed using non-unicode byte strings. :param tagset: The name...
js850/pele
pele/systems/molecularsystem.py
Python
gpl-3.0
861
0.012776
from pele.systems import BaseSystem import pele.utils.elements.elements as elem # This is a dictionary of element parameters for atoms class MolecularSystem(BaseSystem): """ Representation for a molecular system, this system stores info about atoms, bonds, angles and torsions. It is possible to re...
e ato
ms, bonds, angles and torsions; - read/write PDB and other common formats; - interface between different formats of input files for CHARMM, AMBER etc.; - visualise molecular structures; - measure distances between structures. """ def __init__(self): atoms = [] bon...
alfa-addon/addon
plugin.video.alfa/channels/sexgalaxy.py
Python
gpl-3.0
4,331
0.009242
# -*- coding: utf-8 -*- import sys PY3 = False if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if PY3: import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo else: import urlparse # Usamos...
rl, timeout=3).data patron = '<article id="post-.*?' patron += '<a href="([^"]+)" rel="bookmark">([^<]+)<.*?' patron += '<img src="([^"]+)"' matches = re.compile(patron, re.DOTALL).findall(data) for scrapedurl, scrapedtitle, scrapedthumbnail in matches: scrapedplot = "" if not "manyv...
apedurl, thumbnail=scrapedthumbnail, plot=scrapedplot)) next_page = scrapertools.find_single_match(data, '<div class="nav-previous"><a href="([^"]+)"') if next_page != "": itemlist.append(item.clone(action="lista", title="[COLOR blue]Página Siguiente >>[/COLOR]", url=next_page)) return itemlist de...
cloudify-cosmo/softlayer-python
SoftLayer/testing/fixtures/SoftLayer_Product_Order.py
Python
mit
433
0
verifyOrd
er = { 'orderId': 1234, 'orderDate': '2013-08-01 15:23:45', 'prices': [{ 'id': 1, 'laborFee': '2', 'oneTimeFee': '2', 'oneTimeFeeTax': '.1', 'quantity': 1, 'recurringFee': '2', 'recurringFeeTax': '.1', 'hourlyRecurringFee': '2', 'setupF...
der
DistrictDataLabs/yellowbrick
yellowbrick/model_selection/__init__.py
Python
apache-2.0
818
0.001222
# yellowbrick.model_selection # Visualizers that wrap the model selection libraries of Scikit-Learn # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Fri Mar 30 10:36:12 2018 -0400 # # ID: __init__.py [c5355ee] benjamin@bengfort.co
m $ """ Visualizers that wrap the model selection libraries of Scikit-Learn """ ########################################################################## ## Imports ##########################################################################
from .learning_curve import LearningCurve, learning_curve from .validation_curve import ValidationCurve, validation_curve from .cross_validation import CVScores, cv_scores # RFECV and Feature Importances moved here as of YB v1.0 from .importances import FeatureImportances, feature_importances from .rfecv import RFEC...
johmathe/keras
tests/auto/keras/layers/test_convolutional.py
Python
mit
6,580
0.001976
import unittest import numpy as np from numpy.testing import assert_allclose import theano from keras.layers import convolutional class TestConvolutions(unittest.TestCase): def test_convolution_1d(self): nb_samples = 9 nb_steps = 7 input_dim = 10 filter_length = 6 nb_filte...
out = layer.get_output(train).eval() if border_mode == 'same' and subsample == (1, 1): assert out.shape[2:] == input.shape[2:] config = layer.get_c
onfig() def test_maxpooling_2d(self): nb_samples = 9 stack_size = 7 input_nb_row = 11 input_nb_col = 12 pool_size = (3, 3) input = np.ones((nb_samples, stack_size, input_nb_row, input_nb_col)) for ignore_border in [True, False]: for stride in [(1...
drglove/SickRage
sickbeard/clients/download_station.py
Python
gpl-3.0
2,700
0.007037
# Authors: # Pedro Jose Pereira Vieito <pvieito@gmail.com> (Twitter: @pvieito) # # URL: https://github.com/mr-orange/Sick-Beard # # This file is part of SickRage. # # SickRage 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 Softwa...
return None return self.auth def _add_torrent_uri(self, result): data = {'api':'SYNO.D
ownloadStation.Task', 'version':'1', 'method':'create', 'session':'DownloadStation', '_sid':self.auth, 'uri':result.url } if sickbeard.TORRENT_PATH: data['destination'] = sickbeard.TORRENT_PATH self._request(meth...
bitcoinclassic/bitcoinclassic
qa/rpc-tests/mempool_limit.py
Python
mit
2,225
0.007191
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Test mempool limiting together/eviction with the wallet from test_framework.test_framework import Bitc...
_confirmed_utxos(self.relayfee, self.nodes[0], 90) #create a mempool tx that will be evicted us0 = utxos.pop() inputs = [{ "txid" : us0["txid"], "vout" : us0["vout"]}] outputs = {self.nodes[0].getnewaddress() : 0.0001} tx = self.nodes[0].createraw
transaction(inputs, outputs) self.nodes[0].settxfee(self.relayfee) # specifically fund this tx with low fee txF = self.nodes[0].fundrawtransaction(tx) self.nodes[0].settxfee(0) # return to automatic fee selection txFS = self.nodes[0].signrawtransaction(txF['hex']) txid = self.nod...
netvigator/myPyPacks
pyPacks/Web/WantLinks.py
Python
gpl-2.0
2,653
0.026008
#!/usr/bin/pythonTest # -*- coding: utf-8 -*- # # Web functions want links # # 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 vers...
s/gpl.html # # Copyright 2015-2016 Rick Graves # def getUniqueLinks( sReadFile, sOutFile ): # from File.Get import getListFromFileLines from File.Write import QuickDumpLines # from Web.Address import getHostPathTuple, getDomainOffURL from Web.Test import isURL # lLin...
ileLines( sReadFile ) # setLinks= frozenset( filter( isURL, lLines ) ) # # lDecorate = [ ( getHostPathTuple( sURL ), sURL ) for sURL in setLinks ] # lDecorate = [ ( ( getDomainOffURL( t[0][0] ), t[0][1] ), t[1] ) for t in lDecorate ] # lDecorate.sort() # lLinks = [ t[1] for ...
wkentaro/termsaver
termsaverlib/screen/urlfetcher.py
Python
apache-2.0
2,181
0.001834
############################################################################### # # file: urlfetcher.py # # Purpose: refer to module documentation for details # # Note: This file is part of Termsaver application, and should not be used # or executed separately. # #####################################...
message_no_url(self): """ """ return _(""" You just need to provide the URL fr
om where %(app_title)s will read and display on screen. If you do not have any idea which URL to use, check out some examples here: RFC RFC-1034 - http://tools.ietf.org/rfc/rfc1034.txt See a RFC list from Wikipedia: http://en.wikipedia.org/wiki/List_of_RFCs (remember to use th...
ajylee/gpaw-rtxs
gpaw/test/aluminum_testcell.py
Python
gpl-3.0
1,942
0.026262
import numpy as np import sys import os import time from ase import Atom, Atoms from ase.visualize import view from ase.units import Bohr from ase.structure import bulk from gpaw import GPAW from gpaw.atom.basis import BasisMaker from gpaw.response.df import DF from gpaw.mpi import serial_comm, rank, size from gpaw.uti...
= DF(calc='Al2.gpw', q=q, w=w, eta=0.2, ecut=50) #df.write('Al.pckl') df.get_EELS_spectrum(filename='EELS_Al_2') d1 = np.loadtxt('EELS_Al_1') d2 = np.loadtxt('EELS_Al_2') error1 = (d1[1:,1] - d2[1:,1]) / d1[1:,1] * 100 error2 = (d1[1:,2] - d2[1:,2]) / d1[1:,2] * 100 if error1.max() > 0.2 or error2.max()
> 0.2: # percent print error1.max(), error2.max() raise ValueError('Pls check spectrum !') #if rank == 0: # os.remove('Al1.gpw') # os.remove('Al2.gpw')
centrofermi/e3monitor
stats/e3sTrackDayStation.py
Python
gpl-3.0
3,202
0.004685
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Tue 31 May 2016 @author: Fabrizio Coccetti (fabrizio.coccetti@centrofermi.it) [www.fc8.net] Query Run Db and extract several infos """ import os import MySQLdb from datetime import datetime, timedelta import ConfigParser import logging import logging.config...
host, user)) db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname) cur = db.cursor() # Query for the number of tracks every month logger.info('Queries of the total nu
mber of Tracks') query = "SELECT SUM(num_track_events) from runs2 WHERE (run_date = %s) AND station_name = %s;" logger.info("Exec loop: " + query) for _lastDay in daterange(startRun, endRun): _lastDayStr = _lastDay.strftime("%Y-%m-%d") # writing date to file w.write(_lastDayStr + ',') # Loop for each st...
airbnb/airflow
airflow/contrib/operators/emr_terminate_job_flow_operator.py
Python
apache-2.0
1,226
0.001631
# # 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...
of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific...
cated. Please use `airflow.providers.amazon.aws.operators.emr_terminate_job_flow`.""" import warnings # pylint: disable=unused-import from airflow.providers.amazon.aws.operators.emr_terminate_job_flow import EmrTerminateJobFlowOperator # noqa warnings.warn( "This module is deprecated. Please use `airflow.provid...
rogerhu/django
django/db/models/fields/__init__.py
Python
bsd-3-clause
63,210
0.00068
from __future__ import unicode_literals import collections import copy import datetime import decimal import math import warnings from base64 import b64decode, b64encode from itertools import tee from django.db import connection from django.db.models.loading import get_model from django.db.models.query_utils import Q...
ter = Field.auto_creation_counter Field.auto_creation_counter -= 1 else: self.creation_counter = Field.creation_counter Field.creation_counter += 1 self._validators = validators # Store for deconstruction later self.validators = self.default_validators + val...
reversed(self.__class__.__mro__): messages.update(getattr(c, 'default_error_messages', {})) messages.update(error_messages or {}) self._error_messages = error_messages # Store for deconstruction later self.error_messages = messages def deconstruct(self): """ Re...