commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
|---|---|---|---|---|---|---|---|
7bf84875d5999a537a5689df4c1bb9ff6ce950ae
|
Remove forgotten test link
|
src/app/sameas/plugin.py
|
src/app/sameas/plugin.py
|
'''
Created on 4 Nov 2013
@author: cmarat
'''
from flask import request, jsonify
from flask.ext.login import login_required
import requests
from app import app
SAMEAS_URL = "http://sameas.org/json"
@app.route('/sameas', methods=['POST'])
@login_required
def link_to_sameas():
# Retrieve the article from the post
article = request.get_json()
article_id = article['article_id']
app.logger.debug("Running sameAs.org plugin for article {}".format(article_id))
# Get article links
match_items = article['links']
match_items.append({u'link': u'http://dbpedia.org/resource/Resource_Description_Framework', u'id': 9999})
matches = {}
for item in match_items:
item_link = item['link']
original_qname = "figshare_{}".format(item['id'])
# Query sameas.org
response = requests.get(SAMEAS_URL, params={'uri': item_link})
hits = response.json()
# Make a list of all links returned by sameas.org
sameas_links = [uri for h in hits for uri in h['duplicates'] if uri != item_link]
for uri in sameas_links:
# Create the match dictionary
match = {'type': "mapping",
'uri': uri,
'web': uri,
'show': uri,
'original':original_qname}
# Append it to all matches
matches[uri] = match
if matches == {} :
matches = None
# Return the matches
return jsonify({'title':'sameAs.org links','urls': matches})
|
Python
| 0
|
@@ -545,118 +545,8 @@
ks'%5D
-%0A match_items.append(%7Bu'link': u'http://dbpedia.org/resource/Resource_Description_Framework', u'id': 9999%7D)
%0A%0A
|
e5e872d48db28237129fa8c4ebdb76e93dd05954
|
Fix bug in casting variables when cuda is enabled
|
rbm.py
|
rbm.py
|
import torch
class RBM():
def __init__(self, num_visible, num_hidden, k, learning_rate=1e-3, momentum_coefficient=0.5, weight_decay=1e-4, use_cuda=True):
self.num_visible = num_visible
self.num_hidden = num_hidden
self.k = k
self.learning_rate = learning_rate
self.momentum_coefficient = momentum_coefficient
self.weight_decay = weight_decay
self.use_cuda = use_cuda
self.weights = torch.randn(num_visible, num_hidden) * 0.1
self.visible_bias = torch.ones(num_visible) * 0.5
self.hidden_bias = torch.zeros(num_hidden)
self.weights_momentum = torch.zeros(num_visible, num_hidden)
self.visible_bias_momentum = torch.zeros(num_visible)
self.hidden_bias_momentum = torch.zeros(num_hidden)
if self.use_cuda:
self.weights = self.weights.cuda()
self.visible_bias = self.visible_bias.cuda()
self.hidden_bias = self.hidden_bias.cuda()
self.weights_momentum = self.weights_momentum.cuda()
self.visible_bias_momentum = self.visible_bias_momentum.cuda()
self.hidden_bias_momentum = self.hidden_bias_momentum.cuda()
def sample_hidden(self, visible_probabilities):
hidden_activations = torch.matmul(visible_probabilities, self.weights) + self.hidden_bias
hidden_probabilities = self._sigmoid(hidden_activations)
return hidden_probabilities
def sample_visible(self, hidden_probabilities):
visible_activations = torch.matmul(hidden_probabilities, self.weights.t()) + self.visible_bias
visible_probabilities = self._sigmoid(visible_activations)
return visible_probabilities
def contrastive_divergence(self, input_data):
# Positive phase
positive_hidden_probabilities = self.sample_hidden(input_data)
positive_hidden_activations = (positive_hidden_probabilities >= self._random_probabilities(self.num_hidden)).type(torch.FloatTensor)
positive_associations = torch.matmul(input_data.t(), positive_hidden_activations)
# Negative phase
hidden_activations = positive_hidden_activations
for step in range(self.k):
visible_probabilities = self.sample_visible(hidden_activations)
hidden_probabilities = self.sample_hidden(visible_probabilities)
hidden_activations = (hidden_probabilities >= self._random_probabilities(self.num_hidden)).type(torch.FloatTensor)
negative_visible_probabilities = visible_probabilities
negative_hidden_probabilities = hidden_probabilities
negative_associations = torch.matmul(negative_visible_probabilities.t(), negative_hidden_probabilities)
# Update parameters
self.weights_momentum *= self.momentum_coefficient
self.weights_momentum += (positive_associations - negative_associations)
self.visible_bias_momentum *= self.momentum_coefficient
self.visible_bias_momentum += torch.sum(input_data - negative_visible_probabilities, dim=0)
self.hidden_bias_momentum *= self.momentum_coefficient
self.hidden_bias_momentum += torch.sum(positive_hidden_probabilities - negative_hidden_probabilities, dim=0)
batch_size = input_data.size(0)
self.weights += self.weights_momentum * self.learning_rate / batch_size
self.visible_bias += self.visible_bias_momentum * self.learning_rate / batch_size
self.hidden_bias += self.hidden_bias_momentum * self.learning_rate / batch_size
self.weights -= self.weights * self.weight_decay # L2 weight decay
# Compute reconstruction error
error = torch.sum((input_data - negative_visible_probabilities)**2)
return error
def _sigmoid(self, x):
return 1 / (1 + torch.exp(-x))
def _random_probabilities(self, num):
random_probabilities = torch.rand(num)
if self.use_cuda:
random_probabilities = random_probabilities.cuda()
return random_probabilities
|
Python
| 0
|
@@ -1967,38 +1967,22 @@
idden)).
-type(torch.FloatTensor
+float(
)%0A
@@ -2444,30 +2444,14 @@
n)).
-type(torch.FloatTensor
+float(
)%0A%0A
|
157a0f4c4c28ba3ead766bfe2150f4d8cf602594
|
add 'enabled' backup configuration option to specify whether a backup job should be processed
|
rbt.py
|
rbt.py
|
#!/usr/bin/env python3
#
# apt-get install python3-tz python3-yaml
#
import argparse
import collections
import datetime
import os
import subprocess
import time
import typing
import pytz
import yaml
# BackupProperties defines standard set of backup configuration properties
BackupProperties = dict(name=None, template=None, target=None, backups=28,
files=None, exclude=None, fakesuper=False, chown=None)
def verbose_print(msg: str, *args: list, **kwargs: dict) -> None:
"""Print message if verbose flag has been set"""
if cmd_args.verbose:
print(msg, *args, **kwargs)
class FileLock(object):
"""Implement simple file locking"""
def __init__(self, name: str) -> None:
"""Class constructor"""
self.name = name
self.acquired = False
def __enter__(self) -> 'FileLock':
"""Acquire lock"""
if self.acquired:
return self
# make sure process is not already running
if os.path.exists(self.name):
try:
pid = int(open(self.name, 'r').read())
try:
os.kill(pid, 0)
return self
except OSError:
pass
except ValueError:
pass
# acquire lock
with open(self.name, 'w+') as fh:
fh.write(str(os.getpid()))
self.acquired = True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Release acquired lock"""
if self.acquired:
os.unlink(self.name)
self.acquired = False
class Backup(collections.namedtuple('Backup', BackupProperties.keys())):
"""Backup object represents a backup job and its properties"""
@property
def latest_dir(self) -> str:
"""Get the full path to the directory of the latest backup"""
return '{0}/backup.0'.format(self.target)
@property
def target_dir(self) -> str:
"""Get the full path to the directory where next backup will go before rotation"""
return '{0}/backup.{1}'.format(self.target, self.backups)
@property
def last_completed(self):
"""Get full name of completed file in last performed backup"""
return '{0}/completed'.format(self.latest_dir)
@property
def lock_file_name(self):
"""Get the name of a lock file for current backup"""
return '{0}/backup.lock'.format(self.target)
@property
def options(self) -> typing.List[str]:
"""Generate list of options used to start rsync sub-process"""
opts = ['/usr/bin/rsync', '-aRH', '--delete', '--stats']
if self.fakesuper:
opts.append('--fake-super')
if self.chown:
opts.append('--chown={0}'.format(self.chown))
opts.append('--link-dest={0}'.format(self.latest_dir))
for include in self.files or []:
opts.append('root@{0}:{1}'.format(self.name, include))
for exclude in self.exclude or []:
opts.append('--exclude={0}'.format(exclude))
opts.append(self.target_dir)
return opts
def rotate(self) -> None:
"""Rotate backups to move latest backup in backup.0 directory"""
# move target backup out of the way by renaming to backup.tmp
temp_dir = '{0}/backup.tmp'.format(self.target)
os.rename(self.target_dir, temp_dir)
# rotate backups
for idx in range(self.backups - 1, -1, -1):
src = '{0}/backup.{1}'.format(self.target, idx)
dst = '{0}/backup.{1}'.format(self.target, idx + 1)
os.rename(src, dst)
# make target backup last by renaming to backup.0
os.rename(temp_dir, self.latest_dir)
def run(self) -> None:
"""Perform backup with rsync, rotate old backups and save stats"""
# make sure all backup target directories exist
for idx in range(self.backups):
backup_dir = '{0}/backup.{1}'.format(self.target, idx)
if not os.path.isdir(backup_dir):
os.makedirs(backup_dir)
# get start time for later reference
start = time.time()
verbose_print('Starting command: {0}'.format(' '.join(self.options)))
rsync = subprocess.run(self.options, stdout=subprocess.PIPE)
if rsync.returncode not in (24,):
rsync.check_returncode()
self.rotate()
# save statistics from the backup job
with open(self.last_completed, 'w+') as fh:
data = dict(
name=self.name,
timestamp=datetime.datetime.now(pytz.timezone(cmd_args.tz)).isoformat(),
duration=time.time() - start,
)
fh.write(yaml.dump(data, default_flow_style=False))
def load_backups(name: str) -> typing.List[Backup]:
"""Load backup specification from the named file and return Backup object"""
backups = []
templates = {}
with open(name, 'r') as fh:
for items in yaml.load(fh.read()):
# parse templates
for template in items.get('templates', []):
templates[template.get('name')] = template
# parse backups
for backup_item in items.get('servers', []):
backup_config = dict(BackupProperties)
if backup_item.get('template'):
backup_config.update(templates.get(backup_item.get('template', {})))
backup_config.update(**backup_item)
for k, v in backup_config.items():
if type(v) == str:
backup_config[k] = str(v).format(**backup_config)
backups.append(Backup(**backup_config))
return backups
# main program
if __name__ == '__main__':
# parse command line arguments
parser = argparse.ArgumentParser(
description='Perform rsync based incremental backups')
parser.add_argument('--tz', type=str, default='UTC',
help='Current server timezone (default: UTC)')
parser.add_argument('--prefix', type=str, default='/etc/rbt',
help='Configuration directory (default: /etc/rbt)')
parser.add_argument('--config', type=str, action='append', required=True,
help='Specify one or more configuration files')
parser.add_argument('--server', type=str, help='Backup only specified server')
parser.add_argument('--verbose', action='store_true',
help='Print debug info to stdout')
cmd_args = parser.parse_args()
# walk all configuration files
for config in cmd_args.config:
# look for configuration file
if not config.endswith('.yaml'):
config = '{0}.yaml'.format(config)
if not os.path.exists(config):
config = '{0}/{1}'.format(cmd_args.prefix, config)
if not os.path.exists(config):
print('ERROR: Configuration file {0} does not exist.'.format(config))
continue
# run backup job
for backup in load_backups(config):
if cmd_args.server and cmd_args.server != backup.name:
if cmd_args.verbose:
verbose_print('Skipping {0}'.format(backup.name))
continue
with FileLock(backup.lock_file_name) as lock:
if not lock.acquired:
verbose_print('Unable to acquire lock for {0}'.format(backup.name))
continue
verbose_print('Starting backup {0}'.format(backup.name))
backup.run()
|
Python
| 0.000003
|
@@ -344,16 +344,30 @@
kups=28,
+ enabled=True,
%0A
@@ -7079,16 +7079,44 @@
ackup in
+ filter(lambda b: b.enabled,
load_ba
@@ -7120,32 +7120,33 @@
_backups(config)
+)
:%0A if
|
e8c71806e5f10c46fe4ac3e81322e9a44b42f933
|
Simplify todo example
|
test/todo.py
|
test/todo.py
|
"""Incomplete fixes."""
# E501: This should be wrapped similar to how pprint does it
{'2323k2323': 24232323, '2323323232323': 3434343434343434, '34434343434535535': 3434343434343434, '4334343434343': 3434343434}
# See below
{'2323323232323': 3434343434343434,
'2323k2323': 24232323,
'34434343434535535': 3434343434343434,
'4334343434343': 3434343434}
# W601: Handle complicated cases
x = {1: 2}
y = {}
y.has_key(0) + x.has_key(x.has_key(0) + x.has_key(x.has_key(0) + x.has_key(1)))
# E702: Indent correctly when breaking at semicolon
from alnair.exception import (
NoSuchDirectoryError,
NoSuchFileError,
UndefinedPackageError,
); NoSuchDirectoryError; NoSuchFileError; UndefinedPackageError # pyflakes
|
Python
| 0.000563
|
@@ -538,180 +538,39 @@
lon%0A
-from alnair.exception import (%0A NoSuchDirectoryError,%0A NoSuchFileError,%0A UndefinedPackageError,%0A ); NoSuchDirectoryError; NoSuchFileError; UndefinedPackageError
+(%0A 1,%0A 2,%0A 3); 4; 5; 5
#
|
631a231fc2a63dfc0b6d051aa6cef49bd67d80a6
|
add WSGI
|
run.py
|
run.py
|
from app import app
import mapping
import models
if __name__ == "__main__":
models.createDB()
app.run()
|
Python
| 0.001935
|
@@ -43,16 +43,39 @@
models%0A%0A
+wsgi = app.wsgifunc()%0A%0A
if __nam
|
45ede49006c65bc74ab9359e79571e788b8aaebd
|
Fix typo in run.py help
|
run.py
|
run.py
|
#!/usr/bin/python
"""
Thin wrapper around "docker run" which simplifies the creation of a build
environment for XenServer packages.
"""
import argparse
import os
import os.path
import subprocess
import shutil
import sys
import uuid
CONTAINER = "xenserver/xenserver-build-env"
SRPMS_MOUNT_ROOT = "/tmp/docker-SRPMS"
# pylint: disable=C0301
# On OS X with boot2docker there are limits, see:
# http://blog.docker.com/2014/10/docker-1-3-signed-images-process-injection-security-options-mac-shared-directories/ # noqa
# https://github.com/docker/docker/issues/4023
if sys.platform == 'darwin':
HOME = os.getenv("HOME")
if not HOME.startswith("/Users"):
print >> sys.stderr, \
"On OS X $HOME needs to be within /Users for mounting to work"
exit(1)
SRPMS_MOUNT_ROOT = HOME + SRPMS_MOUNT_ROOT
def make_mount_dir():
"""
Make a randomly-named directory under SRPMS_MOUNT_ROOT.
"""
srpm_mount_dir = os.path.join(SRPMS_MOUNT_ROOT, str(uuid.uuid4()))
try:
os.makedirs(srpm_mount_dir)
except OSError:
pass
return srpm_mount_dir
def copy_srpms(srpm_mount_dir, srpms):
"""
Copy each SRPM into the mount directory.
"""
for srpm in srpms:
srpm_name = os.path.basename(srpm)
shutil.copyfile(srpm, os.path.join(srpm_mount_dir, srpm_name))
def main():
"""
Main entry point.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--branch',
help='XenServer branch name. Leave unset unless you'
'plan to build from the internal Citrix repos')
parser.add_argument('-p', '--package', action='append',
help='Packages for which dependencies will '
'be installed')
parser.add_argument('-s', '--srpm', action='append',
help='SRPMs for which dependencies will be installed')
parser.add_argument('-d', '--dir', action='append',
help='Local dir to mount in the '
'image. Will be mounted at /external/<dirname>')
parser.add_argument('--detach', action='store_true',
help='Detach from the container')
parser.add_argument('--rm', action='store_true',
help='Destroy the container on exit')
parser.add_argument('--syslog', action='store_true',
help='Enable syslog to host by mounting in /dev/log')
parser.add_argument('-v', '--volume', action='append',
help='Volume mounts passed directly to docker -v')
args = parser.parse_args(sys.argv[1:])
docker_args = ["docker", "run", "-t", "-u", "builder"]
if args.detach:
if args.rm:
print >> sys.stderr, "--rm not compatible with --detach"
sys.exit(1)
docker_args += ["-d"]
else:
docker_args += ["-i"]
if args.rm:
docker_args += ["--rm=true"]
if args.branch:
docker_args += ["-e", "XS_BRANCH=%s" % args.branch]
# Add package names to the environment
if args.package:
packages = ' '.join(args.package)
docker_args += ['-e', "PACKAGES=%s" % packages]
# Copy all the RPMs to the mount directory
srpm_mount_dir = None
if args.srpm:
srpm_mount_dir = make_mount_dir()
copy_srpms(srpm_mount_dir, args.srpm)
docker_args += ["-v", "%s:/mnt/docker-SRPMS" % srpm_mount_dir]
if args.syslog:
docker_args += ["-v", "/dev/log:/dev/log"]
if args.dir:
for localdir in args.dir:
if not os.path.isdir(localdir):
print "Local directory argument is not a directory!"
sys.exit(1)
ext_path = os.path.abspath(localdir)
int_path = os.path.basename(ext_path)
docker_args += ["-v", "%s:/external/%s" % (ext_path, int_path)]
if args.volume:
for volume in args.volume:
docker_args += ["-v", volume]
# exec "docker run"
docker_args += [CONTAINER, "/usr/local/bin/init-container.sh"]
print >> sys.stderr, "Launching docker with args %s" % docker_args
subprocess.call(docker_args)
if srpm_mount_dir:
print "Cleaning up temporary mount directory"
shutil.rmtree(srpm_mount_dir)
if __name__ == "__main__":
main()
|
Python
| 0.00094
|
@@ -1543,16 +1543,17 @@
less you
+
'%0A
|
0db56e1c005ba3f198be5bfbc1e89d686e693284
|
Fix dinky loop error
|
run.py
|
run.py
|
import json
import textwrap
from GeneticAlgorithm import PhoneOptimize
from celex import Celex
from nist import NIST
'''
fileName: run.py
Authors: Jacob Krantz, Max Dulin
Date Modified: 9/17
- main file to run machine
- Syllabifies a file using NIST or Celex
'''
class Color:
YELLOW = '\033[93m'
BOLD = '\033[1m'
END = '\033[0m'
# runs the probabilistic syllabifier for either a phoneme or file.
def run_s(nist, celex, comparator, hmmbo=None):
obs = " "
while obs != '':
obs = raw_input("Enter filename or phoneme: ")
syl = ""
if "." in obs:
if comparator == "NIST":
nist.syllabify_file(obs, "HMMFiles/outfile.txt", comparator)
else:
celex.syllabify_file(obs, "HMMFiles/outfile.txt", comparator)
elif obs != '':
if comparator == "NIST":
syl = nist.syllabify(obs.lower())
else:
syl = celex.syllabify(hmmbo, obs.lower())
print("Syllabification: " + syl)
# gets the type of syllabifaction that the user wants to do
def get_comparator(config):
comparator_id = 0
while comparator_id not in [1, 2]:
print("\n" + Color.BOLD + "Main Menu" + Color.END)
print "Choose a Comparator:"
print "1. NIST (with Arpabet)"
print "2. CELEX (with DISC)"
try:
comparator_id = int(input())
except:
comparator_id = 0
comparator = "NIST" if comparator_id == 1 else "CELEX"
config["comparator"] = comparator
with open('config.json', 'w') as outfile:
json.dump(config, outfile, sort_keys=True, indent=4)
return comparator
# Ensures correct comparator
def is_legal_selection(cur_comparator, trained_comparator, selection):
if (selection in [1, 4, 5, 6]) or (cur_comparator == trained_comparator):
return True
print "HMM trained in other Comparator. Try retraining"
def load_configuration():
with open('config.json') as json_data_file:
data = json.load(json_data_file)
return data
def main():
nist = NIST()
celex = Celex()
config = load_configuration()
print "----------------------------------------"
print "Welcome to the Probabilistic Syllabifier"
print "----------------------------------------"
comparator = config["comparator"]
trained_comparator = config["comparator"]
choice = 0
hmmbo = None
while choice != 6:
print("\n" + Color.BOLD + "Main Menu" + Color.END)
print("Comparator: " + Color.YELLOW + comparator + Color.END)
option_select = textwrap.dedent(
"""
Choose an option:
1. Train the HMM
2. Run the Syllabifier
3. Test Results
4. Phone Optimization
5. Cross Validate on CELEX
6. Optimize smoothing on CELEX
7. Quit\n"""
)
try:
choice = int(input(option_select))
except ValueError:
choice = 0 # loop again
finally:
if not is_legal_selection(comparator, trained_comparator, choice):
choice = 0
if choice == 1:
if comparator == "NIST":
nist.train_hmm()
else:
hmmbo = celex.input_train_hmm()
trained_comparator = comparator
elif choice == 2:
if(hmmbo == None):
print("Train the system before testing the system. \nPlease use option 1.")
else:
run_s(nist, celex, comparator, hmmbo)
elif choice == 3:
if comparator == "NIST":
nist.test_hmm()
elif(hmmbo == None):
print("Train the system before testing the system. \nPlease use option 1.")
else:
celex.test_hmm(hmmbo)
elif choice == 4:
optimize = PhoneOptimize()
optimize.make_population()
elif choice == 5:
celex.cross_validate()
elif choice == 6:
celex.optimize_smoothing()
if __name__ == '__main__':
main()
|
Python
| 0.000037
|
@@ -2466,17 +2466,17 @@
oice !=
-6
+7
:%0A
|
e7df2d658cdb0a3664b914d0577ea08da2845f08
|
fix run.py python interpreter
|
run.py
|
run.py
|
#!env/bin/python
from api import app
app.run(debug = True)
|
Python
| 0.00052
|
@@ -1,9 +1,11 @@
#!
-env
+flask
/bin
|
603cf4cab90e6655a5aa26269a93376d13dd7fe1
|
Fix package installing
|
lib/pacman/sync.py
|
lib/pacman/sync.py
|
from lib.pacman.command import execute
def refresh_force():
"""pacman -Syy"""
execute('sudo -S pacman -Syy', discard_output=True)
def system_upgrade():
"""pacman -Syu"""
execute('sudo -S pacman -Syu --noconfirm', discard_output=True)
def install(package, asdeps=False):
"""pacman -S [--asdeps] package"""
option = ['--noconfirm', '--needed']
if asdeps:
option.append('--asdeps')
command = 'sudo -S pacman -S {} {}'.format(' '.join(option), package)
execute(command, discard_output=True)
def exist(package):
"""check 'pacman -Si package' return code"""
result = execute('pacman -Ss "^{}$"'.format(package))
return not bool(result.returncode)
|
Python
| 0
|
@@ -479,24 +479,33 @@
ption),
+' '.join(
package)
%0A exe
@@ -496,16 +496,17 @@
package)
+)
%0A exe
|
8358796cb469f2e4b437877ea2d4d1043defdc59
|
Disable verbose logging for tests
|
tests/run.py
|
tests/run.py
|
#!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Leo (Chong Liu)" <HiddenPython@gmail.com>',
]
import sys
import os
HERE = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
'..'))
appengine_location = os.path.join(HERE, 'thirdparty', 'google_appengine')
extra_paths = [HERE,
os.path.join(appengine_location, 'lib', 'django'),
os.path.join(appengine_location, 'lib', 'webob'),
os.path.join(appengine_location, 'lib', 'yaml', 'lib'),
os.path.join(appengine_location, 'lib', 'antlr3'),
appengine_location,
os.path.join(HERE, 'app'),
os.path.join(HERE, 'thirdparty', 'coverage'),
]
import nose
from nose import plugins
import logging
log = logging.getLogger('nose.plugins.cover')
def begin(self):
"""Used to stub out nose.plugins.cover.Coverage.begin.
The difference is that it loads Melange after coverage starts, so
the loading of models, logic and views can be tracked by coverage.
"""
log.debug("Coverage begin")
import coverage
self.skipModules = sys.modules.keys()[:]
if self.coverErase:
log.debug("Clearing previously collected coverage statistics")
coverage.erase()
coverage.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]')
coverage.start()
load_melange()
def load_melange():
"""Prepare Melange for usage.
Registers a core, the GSoC and GCI modules, and calls the sitemap, sidebar
and rights services.
"""
from soc.modules import callback
from soc.modules.core import Core
# Register a core for the test modules to use
callback.registerCore(Core())
current_core = callback.getCore()
modules = ['gsoc', 'gci']
fmt = 'soc.modules.%s.callback'
current_core.registerModuleCallbacks(modules, fmt)
# Make sure all services are called
current_core.callService('registerViews', True)
current_core.callService('registerWithSitemap', True)
current_core.callService('registerWithSidebar', True)
current_core.callService('registerRights', True)
class AppEngineDatastoreClearPlugin(plugins.Plugin):
"""Nose plugin to clear the AppEngine datastore between tests.
"""
name = 'AppEngineDatastoreClearPlugin'
enabled = True
def options(self, parser, env):
return plugins.Plugin.options(self, parser, env)
def configure(self, parser, env):
plugins.Plugin.configure(self, parser, env)
self.enabled = True
def afterTest(self, test):
from google.appengine.api import apiproxy_stub_map
datastore = apiproxy_stub_map.apiproxy.GetStub('datastore')
# clear datastore iff one is available
if datastore is not None:
datastore.Clear()
def main():
sys.path = extra_paths + sys.path
os.environ['SERVER_SOFTWARE'] = 'Development via nose'
os.environ['SERVER_NAME'] = 'Foo'
os.environ['SERVER_PORT'] = '8080'
os.environ['APPLICATION_ID'] = 'test-app-run'
os.environ['USER_EMAIL'] = 'test@example.com'
os.environ['CURRENT_VERSION_ID'] = 'testing-version'
os.environ['HTTP_HOST'] = 'some.testing.host.tld'
import main as app_main
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import datastore_file_stub
from google.appengine.api import mail_stub
from google.appengine.api import user_service_stub
from google.appengine.api import urlfetch_stub
from google.appengine.api.memcache import memcache_stub
from google.appengine.api.taskqueue import taskqueue_stub
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
apiproxy_stub_map.apiproxy.RegisterStub('urlfetch',
urlfetch_stub.URLFetchServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub('user',
user_service_stub.UserServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub('datastore',
datastore_file_stub.DatastoreFileStub('test-app-run', None, None))
apiproxy_stub_map.apiproxy.RegisterStub('memcache',
memcache_stub.MemcacheServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub('mail', mail_stub.MailServiceStub())
yaml_location = os.path.join(HERE, 'app')
apiproxy_stub_map.apiproxy.RegisterStub(
'taskqueue', taskqueue_stub.TaskQueueServiceStub(root_path=yaml_location))
import django.test.utils
django.test.utils.setup_test_environment()
plugins = [AppEngineDatastoreClearPlugin()]
if '--coverage' in sys.argv:
from nose.plugins import cover
plugin = cover.Coverage()
from mox import stubout
stubout_obj = stubout.StubOutForTesting()
stubout_obj.SmartSet(plugin, 'begin', begin)
plugins.append(plugin)
args = ['--with-coverage',
'--cover-package=soc.',
'--cover-erase',
'--cover-html',
'--cover-html-dir=coverageResults']
sys.argv.remove('--coverage')
sys.argv += args
else:
load_melange()
nose.main(addplugins=plugins)
if __name__ == '__main__':
main()
|
Python
| 0.000001
|
@@ -1479,16 +1479,36 @@
cover')%0A
+logging.disable(90)%0A
%0A%0Adef be
|
d7c751ddb71a2e0f1c67c045fcd8c52d8079c3f2
|
fix lib/util/script:make_environment_wrapped_script() converting paths to absolute paths
|
lib/util/script.py
|
lib/util/script.py
|
# Copyright (c) 2017 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Helper function to create script files for pure Python code, ppy modules or
shell commands. Uses the Python #distlib package.
"""
import os
import six
from distlib.scripts import ScriptMaker
argschema = require('../argschema')
def make_python_script(script_name, directory, code):
"""
Uses #distlib.scripts.ScriptMaker to create a Python script that is invoked
with this current interpreter. The script runs *code* and will be created
in the specified *directory*.
# Parameters
script_name (str): The name of the script to create.
directory (str): The directory to create the script in.
code (str): The python code to run.
# Returns
A list of filenames created. Depending on the platform, more than one file
might be created to support multiple use cases (eg. and `.exe` but also a
bash-script on Windows).
"""
if os.name == 'nt' and (not script_name.endswith('.py') \
or not script_name.endswith('.pyw')):
# ScriptMaker._write_script() will split the extension from the script
# name, thus if there is an extension, we should add another suffix so
# the extension doesn't get lost.
script_name += '.py'
maker = ScriptMaker(None, directory)
maker.clobber = True
maker.variants = set(('',))
maker.set_mode = True
maker.script_template = code
return maker.make(script_name + '=isthisreallynecessary')
def make_command_script(script_name, directory, args):
"""
Uses #make_python_script() to create a Python script that uses the
#subprocess module to run the command specified with *args*.
"""
argschema.validate('args', args, {'type': [list, tuple],
'items': {'type': six.text_type}})
code = 'import subprocess\n'\
'import sys\n'\
'sys.exit(subprocess.call({!r}))\n'.format(args)
return make_python_script(script_name, directory, code)
def make_nodepy_script(script_name, directory, filename, reference_dir=None):
"""
Uses #make_python_script() to create a script that invokes the current
python and ppy runtime to run the ppy module specified by *filename*.
If a *reference_dir* is specified, that directory will be used as a
the base directory to start searching for `ppy_modules/` directories
instead of the current working directory.
"""
argschema.validate('filename', filename, {'type': six.text_type})
argschema.validate('reference_dir', reference_dir, {'type': [six.text_type, None]})
args = []
if reference_dir:
# Find modules in the reference directory.
args.append('--current-dir')
args.append(reference_dir)
args.append(filename)
code = 'import sys\n'\
'import nodepy\n'\
'sys.argv = [sys.argv[0]] + {args!r} + sys.argv[1:]\n'\
'sys.exit(nodepy.main())\n'.format(args=args)
return make_python_script(script_name, directory, code)
def make_environment_wrapped_script(script_name, directory, target_program,
path=(), pythonpath=()):
"""
Creates a Python wrapper script that will invoke *target_program*. Before
the program is invoked, the environment variables PATH and PYTHONPATH will
be prefixed with the paths from *path* and *pythonpath*.
"""
argschema.validate('target_program', target_program, {'type': six.text_type})
argschema.validate('path', path, {'type': [tuple, list], 'items': {'type': six.text_type}})
argschema.validate('pythonpath', pythonpath, {'type': [tuple, list], 'items': {'type': six.text_type}})
if not os.path.isabs(target_program):
raise ValueError('target_program must be an absolute path')
code = 'import os, subprocess, sys\n'\
'os.environ["PATH"] = os.pathsep.join({path!r}) + os.pathsep + os.environ.get("PATH", "")\n'\
'os.environ["PYTHONPATH"] = os.pathsep.join({pythonpath!r}) + os.pathsep + os.environ.get("PYTHONPATH", "")\n'\
'sys.exit(subprocess.call([{program!r}] + sys.argv[1:]))\n'.format(path=path, pythonpath=pythonpath, program=target_program)
return make_python_script(script_name, directory, code)
|
Python
| 0.00003
|
@@ -4632,16 +4632,117 @@
path')%0A%0A
+ path = %5Bos.path.abspath(x) for x in path%5D%0A pythonpath = %5Bos.path.abspath(x) for x in pythonpath%5D%0A%0A
code =
|
612c809a68640fea9130952fdd626ee0118646bb
|
Fix code style for task group model
|
src/ggrc_workflows/models/task_group.py
|
src/ggrc_workflows/models/task_group.py
|
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
from ggrc import db
from ggrc.models.mixins import (
Titled, Slugged, Described, Timeboxed, WithContact
)
from ggrc.models.associationproxy import association_proxy
from ggrc.models.reflection import PublishOnly
class TaskGroup(
WithContact, Timeboxed, Described, Titled, Slugged, db.Model):
__tablename__ = 'task_groups'
_title_uniqueness = False
workflow_id = db.Column(
db.Integer, db.ForeignKey('workflows.id'), nullable=False)
lock_task_order = db.Column(db.Boolean(), nullable=True)
task_group_objects = db.relationship(
'TaskGroupObject', backref='task_group', cascade='all, delete-orphan')
objects = association_proxy(
'task_group_objects', 'object', 'TaskGroupObject')
task_group_tasks = db.relationship(
'TaskGroupTask', backref='task_group', cascade='all, delete-orphan')
cycle_task_groups = db.relationship(
'CycleTaskGroup', backref='task_group')
sort_index = db.Column(
db.String(length=250), default="", nullable=False)
_publish_attrs = [
'workflow',
'task_group_objects',
PublishOnly('objects'),
'task_group_tasks',
'lock_task_order',
'sort_index',
# Intentionally do not include `cycle_task_groups`
#'cycle_task_groups',
]
def copy(self, _other=None, **kwargs):
columns = [
'title', 'description', 'workflow', 'sort_index', 'modified_by', 'context'
]
if(kwargs.get('clone_people', False)):
columns.append('contact')
target = self.copy_into(_other, columns, **kwargs)
if kwargs.get('clone_objects', False):
self.copy_objects(target, **kwargs)
if kwargs.get('clone_tasks', False):
self.copy_tasks(target, **kwargs)
return target
def copy_objects(self, target, **kwargs):
for task_group_object in self.task_group_objects:
target.task_group_objects.append(
task_group_object.copy(
task_group=target,
context=target.context,
))
return target
def copy_tasks(self, target, **kwargs):
for task_group_task in self.task_group_tasks:
target.task_group_tasks.append(
task_group_task.copy(None,
task_group=target,
context=target.context,
clone_people=kwargs.get("clone_people", False),
))
return target
|
Python
| 0.001611
|
@@ -344,14 +344,10 @@
act%0A
-
)%0A
+
from
@@ -467,16 +467,20 @@
kGroup(%0A
+
With
@@ -538,16 +538,16 @@
Model):%0A
-
__tabl
@@ -1474,16 +1474,17 @@
%0A #
+
'cycle_t
@@ -1496,20 +1496,16 @@
roups',%0A
-
%5D%0A%0A d
@@ -1630,16 +1630,24 @@
ied_by',
+%0A
'contex
@@ -1649,20 +1649,16 @@
ontext'%0A
-
%5D%0A%0A
@@ -2108,33 +2108,24 @@
ects.append(
-%0A
task_group_o
@@ -2138,34 +2138,32 @@
copy(%0A
-
task_group=targe
@@ -2167,34 +2167,32 @@
rget,%0A
-
-
context=target.c
@@ -2195,26 +2195,24 @@
et.context,%0A
-
))%0A%0A
@@ -2228,17 +2228,16 @@
target%0A%0A
-%0A
def co
@@ -2357,25 +2357,16 @@
.append(
-%0A
task_gro
@@ -2378,16 +2378,27 @@
sk.copy(
+%0A
None,%0A
@@ -2516,20 +2516,16 @@
False),%0A
-
))
|
70b00ee903fac46038bafdd69dd8e643d6cc76ad
|
Fix setting "auto" flag with pkgng
|
libpb/pkg/pkgng.py
|
libpb/pkg/pkgng.py
|
"""
The next generation package management tools (i.e. pkgng)..
"""
from __future__ import absolute_import
import os
from libpb import env
__all__ = ["add", "change", "info", "query", "remove"]
suffix = ".txz"
shell_pkg_add = """
if [ ! -d %(wrkdir)s ]; then
mkdir -p %(wrkdir)s;
clean_wrkdir="YES";
fi;
tar -xf %(pkgfile)s -C %(wrkdir)s -s ",/.*/,,g" "*/pkg-static";
%(wrkdir)s/pkg-static add %(pkgfile)s;
rm -f %(wrkdir)s/pkg-static;
if [ "$clean_wrkdir" = "YES" ]; then
rmdir %(wrkdir)s || true;
fi
"""
os.environ["ASSUME_ALWAYS_YES"] = "YES"
def add(port, repo=False, pkg_dir=None):
"""Add a package for port."""
if port.attr["pkgname"].rsplit('-', 1)[0] == "pkg":
# Special case when adding the `pkg' as it provides the functionality
# and thus cannot add itself (or so one would thing).
if repo or pkg_dir:
# TODO: support installing ``pkg'' from a custom $PKGDIR
args = False
else:
args = ("sh", "-ec", shell_pkg_add % port.attr)
else:
# Normal package add
if repo:
args = ("pkg", "install", "-y", port.attr["pkgname"])
elif pkg_dir:
pkgfile = os.path.join(pkg_dir, port.attr["pkgname"] + suffix)
args = ("pkg", "add", pkgfile)
else:
args = ("pkg", "add", port.attr["pkgfile"])
return args
def change(port, prop, value):
"""Change a property of a package,"""
if prop == "explicit":
auto = "0" if value else "1"
return ("pkg", "set", "-ya", auto, port.attr["pkgname"])
else:
assert not "unknown package property '%s'" % prop
def info(repo=False):
"""List all installed packages with their respective port origin."""
pkg_info = env.flags["chroot"] + "/usr/local/sbin/pkg"
if not os.path.isfile(pkg_info):
return False
if repo:
return ("pkg", "rquery", "%n-%v:%o")
else:
return ("pkg", "query", "%n-%v:%o")
def query(port, prop, repo=False):
"""Query q property of a package."""
args = ("pkg", "rquery" if repo else "query", "-F", port.attr["pkgname"])
if prop == "config":
args += ("%Ok %Ov",)
else:
assert not "unknown package property '%s'" % prop
return args
def remove(pkgs):
"""Remove a package for a port."""
return ("pkg", "delete", "-fy") + pkgs
|
Python
| 0
|
@@ -1545,17 +1545,17 @@
et%22, %22-y
-a
+A
%22, auto,
|
0026536a68dfc58bc3e9ef89fc2e104287c30d67
|
Fix bug where metadata is not written
|
src/create-extracts/create_extracts.py
|
src/create-extracts/create_extracts.py
|
#!/usr/bin/env python
"""Generate jobs for rendering tiles in pyramid and list format in JSON format
Usage:
create_extracts.py bbox <source_file> <tsv_file> [--patch-from=<patch-src>] [--upload] [--concurrency=<concurrency>] [--target-dir=<target-dir>]
create_extracts.py zoom-level <source_file> --max-zoom=<max-zoom> [--upload] [--target-dir=<target-dir>]
create_extracts.py (-h | --help)
create_extracts.py --version
Options:
-h --help Show this screen.
--version Show version.
--upload Upload extracts to S3.
--patch-from=<patch-src> Patch MBTiles file with other MBTiles src.
--concurrency=<concurrency> Number of copy processes to use [default: 4].
--max-zoom=<max-zoom> Max zoom level of low zoom level extract.
--target-dir=<target-dir> Target directory to put extracts in [default: ./]
"""
import shutil
import subprocess
import sqlite3
import csv
import os.path
from multiprocessing.dummy import Pool as ProcessPool
from docopt import docopt
ATTRIBUTION = '<a href="http://www.openstreetmap.org/about/" target="_blank">© OpenStreetMap contributors</a>'
VERSION = '2.0'
class Extract(object):
def __init__(self, extract, country, city, top, left, bottom, right,
min_zoom=0, max_zoom=14, center_zoom=10):
self.extract = extract
self.country = country
self.city = city
self.min_lon = left
self.min_lat = bottom
self.max_lon = right
self.max_lat = top
self.min_zoom = min_zoom
self.max_zoom = max_zoom
self.center_zoom = center_zoom
def bounds(self):
return '{},{},{},{}'.format(self.min_lon, self.min_lat,
self.max_lon, self.max_lat)
def center(self):
center_lon = (self.min_lon + self.max_lon) / 2.0
center_lat = (self.min_lat + self.max_lat) / 2.0
return '{},{},{}'.format(center_lat, center_lon, self.center_zoom)
def metadata(self, extract_file):
return {
"type": "baselayer",
"attribution": ATTRIBUTION,
"version": VERSION,
"minzoom": self.min_zoom,
"maxzoom": self.max_zoom,
"name": "osm2vectortiles",
"id": "osm2vectortiles",
"description": "Extract from http://osm2vectortiles.org",
"bounds": self.bounds(),
"center": self.center(),
"basename": os.path.basename(extract_file),
"filesize": os.path.getsize(extract_file)
}
def create_extract(extract, source_file, extract_file):
source = 'mbtiles://' + os.path.abspath(source_file)
sink = 'mbtiles://' + os.path.abspath(extract_file)
print('Bounds: {}'.format(extract.bounds()))
cmd = [
'tilelive-copy',
'--bounds={}'.format(extract.bounds()),
'--minzoom', str(extract.min_zoom),
'--maxzoom', str(extract.max_zoom),
'--timeout=200000',
source, sink
]
subprocess.check_call(cmd)
def update_metadata(mbtiles_file, metadata):
"""
Update metadata key value pairs inside the MBTiles file
with the provided metadata
"""
conn = sqlite3.connect(mbtiles_file)
def upsert_entry(key, value):
conn.execute("DELETE FROM metadata WHERE name='{}'".format(key))
conn.execute("INSERT INTO metadata VALUES('{}', '{}')".format(key, value))
for key, value in metadata.items():
upsert_entry(key, value)
def parse_extracts(tsv_file):
with open(args['<tsv_file>'], "r") as file_handle:
reader = csv.DictReader(file_handle, delimiter='\t', )
for row in reader:
yield Extract(
row['extract'],
row['country'],
row['city'],
float(row['top']),
float(row['left']),
float(row['bottom']),
float(row['right'])
)
def upload_mbtiles(mbtiles_file):
"""
Use s3cmd to upload file. This is easier than using Boto directly.
The upload command is configured via environment variables and not
the extract utility command line flags.
"""
config_file = os.getenv('S3_CONFIG_FILE',
os.path.join(os.environ['HOME'], '.s3cfg'))
access_key = os.environ['S3_ACCESS_KEY']
secret_key = os.environ['S3_SECRET_KEY']
bucket_name = os.getenv('S3_BUCKET_NAME', 'osm2vectortiles-downloads')
prefix = os.getenv('S3_PREFIX', 'v{}/{}/'.format(VERSION, 'extracts'))
subprocess.check_call([
's3cmd',
'--config={}'.format(config_file),
'--access_key={}'.format(access_key),
'--secret_key={}'.format(secret_key),
'put', mbtiles_file,
's3://{}/{}'.format(bucket_name, prefix),
'--acl-public',
'--multipart-chunk-size-mb=50'
])
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
target_dir = args['--target-dir']
upload = args['--upload']
source_file = args['<source_file>']
def process_extract(extract):
extract_file = os.path.join(target_dir, extract.extract + '.mbtiles')
print('Create extract {}'.format(extract_file))
# Instead of patching copy over the patch source as target and
# write directly to it (since that works concurrently).
patch_src = args['--patch-from']
if patch_src:
print('Use patch from {} as base'.format(patch_src))
shutil.copyfile(patch_src, extract_file)
create_extract(extract, source_file, extract_file)
print('Update metadata {}'.format(extract_file))
update_metadata(extract_file, extract.metadata(extract_file))
if upload:
print('Upload file {}'.format(extract_file))
upload_mbtiles(extract_file)
if args['bbox']:
process_count = int(args['--concurrency'])
extracts = list(parse_extracts(args['<tsv_file>']))
pool = ProcessPool(process_count)
pool.map(process_extract, extracts)
pool.close()
pool.join()
if args['zoom-level']:
max_zoom_level = int(args['--max-zoom'])
extract = Extract('world_z0-z{}'.format(max_zoom_level),
country=None,
city=None,
left=-180,
right=180,
top=85.0511,
bottom=-85.0511,
center_zoom=2,
min_zoom=0,
max_zoom=max_zoom_level
)
process_extract(extract)
|
Python
| 0.000001
|
@@ -3532,16 +3532,52 @@
value)%0A%0A
+ conn.commit()%0A conn.close()%0A%0A
%0Adef par
|
01bff2cb28dedb98e5ac16d35178569a8ca8bbe1
|
improve readability
|
src/graphql/pyutils/suggestion_list.py
|
src/graphql/pyutils/suggestion_list.py
|
from typing import Collection, List
__all__ = ["suggestion_list"]
def suggestion_list(input_: str, options: Collection[str]) -> List[str]:
"""Get list with suggestions for a given input.
Given an invalid input string and list of valid options, returns a filtered list
of valid options sorted based on their similarity with the input.
"""
options_by_distance = {}
lexical_distance = LexicalDistance(input_)
input_threshold = len(input_) // 2
for option in options:
distance = lexical_distance.measure(option)
threshold = max(input_threshold, len(option) // 2, 1)
if distance <= threshold:
options_by_distance[option] = distance
# noinspection PyShadowingNames
return sorted(
options_by_distance,
key=lambda option: (options_by_distance.get(option, 0), option),
)
class LexicalDistance:
"""Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number of edits
needed to transform string A into string B. An edit can be an insertion, deletion,
or substitution of a single character, or a swap of two adjacent characters.
This distance can be useful for detecting typos in input or sorting.
"""
_input: str
_input_lower_case: str
_cells: List[List[int]]
def __init__(self, input_: str):
self._input = input_
self._input_lower_case = input_.lower()
self._cells = []
def measure(self, option: str):
if self._input == option:
return 0
option_lower_case = option.lower()
# Any case change counts as a single edit
if self._input_lower_case == option_lower_case:
return 1
d = self._cells
a, b = option_lower_case, self._input_lower_case
a_len, b_len = len(a), len(b)
d = [[j for j in range(0, b_len + 1)]]
for i in range(1, a_len + 1):
d.append([i] + [0] * b_len)
for i in range(1, a_len + 1):
for j in range(1, b_len + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
return d[a_len][b_len]
|
Python
| 0.000005
|
@@ -2163,230 +2163,434 @@
-d%5Bi%5D%5Bj%5D = min(d%5Bi - 1%5D%5Bj%5D + 1, d%5Bi%5D%5Bj - 1%5D + 1, d%5Bi - 1%5D%5Bj - 1%5D + cost)%0A%0A if i %3E 1 and j %3E 1 and a%5Bi - 1%5D == b%5Bj - 2%5D and a%5Bi - 2%5D == b%5Bj - 1%5D:%0A d%5Bi%5D%5Bj%5D = min(d%5Bi%5D%5Bj%5D, d%5Bi - 2%5D%5Bj - 2%5D + 1)
+current_cell = min(%0A d%5Bi - 1%5D%5Bj%5D + 1, # delete%0A d%5Bi%5D%5Bj - 1%5D + 1, # insert%0A d%5Bi - 1%5D%5Bj - 1%5D + cost, # substitute%0A )%0A%0A if i %3E 1 and j %3E 1 and a%5Bi - 1%5D == b%5Bj - 2%5D and a%5Bi - 2%5D == b%5Bj - 1%5D:%0A # transposition%0A current_cell = min(current_cell, d%5Bi - 2%5D%5Bj - 2%5D + 1)%0A%0A d%5Bi%5D%5Bj%5D = current_cell
%0A%0A
|
cb46b2d3e31dd0af9db9e9df256db6d95c2162e0
|
Fix buggy reset util
|
src/resetutil.py
|
src/resetutil.py
|
# Playhouse: Making buildings into interactive displays using remotely controllable lights.
# Copyright (C) 2014 John Eriksson, Arvid Fahlström Myrman, Jonas Höglund,
# Hannes Leskelä, Christian Lidström, Mattias Palo,
# Markus Videll, Tomas Wickman, Emil Öhman.
#
# 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 distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Resetutil is a simple utility for pairing Philips hue bulbs to bridges.
It is a command-line utility and can be run by executing ``python3 resetutil.py``.
The program will first attempt to list all available bridges in the network.
It will then list all the options and allow you to pick a bridge or write a IP address
if the bridge you want to connect to is not in the list.
Once a bridge has been selected, the program will enter a loop where you can reset as many
lamps as you want. To reset a lamp, plug it in within 30 centimeters from the bridge, make
sure that no other nearby lamps are plugged in, and type "reset".
When you are done with all lamps, type "done".
"""
import datetime
import json
import os
import sys
import socket
import traceback
import tornado.concurrent
import tornado.gen
import tornado.ioloop
import tornado.stack_context
import playhouse
class _StopError(Exception):
pass
def ask_for_y(s):
while True:
prompt = input(s)
if prompt[0] == "y":
break
if prompt[0] == "n":
raise _StopError
@tornado.gen.coroutine
def enter_manual_ip():
while True:
try:
ip = input("Enter manual IP address:")
bridge = yield playhouse.Bridge(ip)
print("Using bridge with MAC adress", bridge.serial_number)
break
except playhouse.NoBridgeFoundException:
print("No bridge found at given adress")
return bridge
@tornado.gen.coroutine
def pick_bridge():
while True:
print("Beginning search for bridges")
bridges = yield playhouse.discover()
bridge_map = dict()
if len(bridges) != 0:
print("Found bridges:")
for b in bridges:
bridge_map[bridges.mac] = bridges
print(bridges.mac)
print("Enter the bridge MAC to pick a bridge")
else:
print("No bridges found")
print("Enter 'manual' to enter a manual IP address")
print("Enter 'search' to search for bridges again")
while True:
i = input(":")
if i == "search":
break
elif i=="manual":
return (yield enter_manual_ip())
else:
bridge = bridge_map.get(i)
if bridge is None:
print("No such bridge exists")
else:
return bridge
def create_user(bridge):
while True:
try:
input("Press bridge link button, so that a new user can be created, press enter afterwards:")
name = yield bridge.create_user("resetutil")
return name
except playhouse.NoLinkButtonPressedException:
print("Failed to create user")
pass
def enter_num(s):
light_num = None
while light_num is None:
try:
light_num = int(input(s))
if light_num <= 0:
raise ValueError
except ValueError:
print("Invalid number, must be a positive integer")
return light_num
def reset_lamp():
resets = 0
while True:
print("Plug in a lamp, and enter 'reset' to reset a lamp")
print("Enter 'done' when all lamps have been reset")
i = input(":")
if i == "reset":
try:
yield bridge.reset_nearby_bulb()
print("Lamp was successfully reset")
resets += 1
except playhouse.BulbNotResetException:
print("Failed to reset lamp")
elif i == "done":
break
return resets
@tornado.gen.coroutine
def do_stuff():
usernames = {}
try:
while True:
print("Make sure that the bridge is factory-reset")
prompt = ask_for_y("Is it (y/n)?")
bridge = yield pick_bridge()
name = create_user()
light_num = yield reset_lamp()
if light_num != 0:
print("All bulbs reset")
input("Plug in all {} reset lamps and press enter:".format(light_num))
yield bridge.search_lights()
while True:
yield tornado.gen.Task(loop.add_timeout, datetime.timedelta(seconds=10))
res = yield bridge.get_new_lights()
if res['lastscan'] != 'active':
del res['lastscan']
print("Found", len(res), "lights")
break
usernames[bridge.serial_number] = name
while True:
prompt = input("Repeat with another bridge(y/n)?")
if prompt == 'y':
break
elif prompt == 'n':
return
except _StopError:
pass
except Exception:
traceback.print_exc()
finally:
if len(usernames) > 0:
print("Write down these MAC addresses and usernames for later use in the web-based "
"configuration system, or copy the newly created bridge_setup.json to "
"the lamp server's root directory.")
print("The usernames are vital in order for the lamp server "
"to be able to communicate with the bridges.")
print("{:<16}{}".format("MAC", "username"))
print("{:<16}{}".format("---", "--------"))
for mac, username in usernames.items():
print("{:<16}{}".format(mac, username))
with open("bridge_setup.json", 'w') as f:
json.dump({"usernames": usernames}, f)
else:
print("No bridges were reset.")
if __name__ == '__main__':
loop = tornado.ioloop.IOLoop.instance()
loop.run_sync(do_stuff)
|
Python
| 0.000001
|
@@ -2730,29 +2730,27 @@
ap%5Bb
-ridges.mac%5D = bridges
+.serial_number%5D = b
%0A
@@ -2773,18 +2773,22 @@
nt(b
-ridges.mac
+.serial_number
)%0A
@@ -3399,16 +3399,38 @@
bridge%0A%0A
+@tornado.gen.coroutine
%0Adef cre
@@ -4076,16 +4076,39 @@
t_num%0A%0A%0A
+@tornado.gen.coroutine%0A
def rese
@@ -4114,16 +4114,22 @@
et_lamp(
+bridge
):%0A r
@@ -4899,16 +4899,22 @@
name =
+ yield
create_
@@ -4918,16 +4918,22 @@
te_user(
+bridge
)%0A%0A
@@ -4968,16 +4968,22 @@
et_lamp(
+bridge
)%0A%0A
|
e37174e733b7b186a40cc82ffe95c3d10014bd2f
|
Check for errors
|
src/redis.py
|
src/redis.py
|
#!/usr/bin/env python
#
# igcollect - Redis
#
# Copyright (c) 2016 InnoGames GmbH
#
from argparse import ArgumentParser
from subprocess import Popen, PIPE
from time import time
def parse_args():
parser = ArgumentParser()
parser.add_argument('--prefix', default='redis')
return parser.parse_args()
def main():
args = parse_args()
redis_info = Popen(('redis-cli', '-a', redis_pwd(), 'info'),
stdout=PIPE).stdout.read()
redis_info = redis_info.splitlines()
redis_stats = {}
for x in redis_info:
if x.find(':') != -1:
key, value = x.split(':')
redis_stats[key] = value
template = args.prefix + '.{} {} ' + str(int(time()))
headers = (
'total_connections_received',
'total_commands_processed',
'keyspace_hits',
'keyspace_misses',
'used_memory',
'used_cpu_sys',
'used_cpu_user',
'used_cpu_sys_children',
'used_cpu_user_children',
)
for metric in headers:
print(template.format(metric, redis_stats[metric]))
def redis_pwd():
"""Get the Redis password from the configuration"""
with open("/etc/redis/redis.conf") as fd:
secret_cfg = fd.read().splitlines()
for line in secret_cfg:
line = line.strip()
if line.startswith("requirepass"):
return line.split(" ")[1].strip()
return ''
if __name__ == '__main__':
main()
|
Python
| 0.000001
|
@@ -78,17 +78,16 @@
GmbH%0A#%0A%0A
-%0A
from arg
@@ -141,19 +141,20 @@
ort
-Popen, PIPE
+check_output
%0Afro
@@ -365,15 +365,22 @@
o =
-Popen((
+check_output(%5B
'red
@@ -417,100 +417,9 @@
nfo'
-),%0A stdout=PIPE).stdout.read()%0A redis_info = redis_info.splitlines(
+%5D
)%0A%0A
@@ -461,16 +461,29 @@
dis_info
+.splitlines()
:%0A
|
9d8de33a72e821bf0fb7415f73ba8cfabc3ba93b
|
Update version 0.7.6 -> 0.7.7
|
src/setup.py
|
src/setup.py
|
#!/usr/bin/env python
#
# Copyright 2012, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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 Google Inc. 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" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 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 IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Set up script for mod_pywebsocket.
"""
from distutils.core import setup
import sys
_PACKAGE_NAME = 'mod_pywebsocket'
if sys.version < '2.3':
print >> sys.stderr, '%s requires Python 2.3 or later.' % _PACKAGE_NAME
sys.exit(1)
setup(author='Yuzo Fujishima',
author_email='yuzo@chromium.org',
description='WebSocket extension for Apache HTTP Server.',
long_description=(
'mod_pywebsocket is an Apache HTTP Server extension for '
'WebSocket (http://tools.ietf.org/html/rfc6455). '
'See mod_pywebsocket/__init__.py for more detail.'),
license='See COPYING',
name=_PACKAGE_NAME,
packages=[_PACKAGE_NAME, _PACKAGE_NAME + '.handshake'],
url='http://code.google.com/p/pywebsocket/',
# See the source of distutils.version, distutils.versionpredicate and
# distutils.dist to understand how to name version numbers.
version='0.7.6',
)
# vi:sts=4 sw=4 et
|
Python
| 0.000001
|
@@ -2483,17 +2483,17 @@
on='0.7.
-6
+7
',%0A
|
1f9947598671422d86c76c036d4037690a3e99ba
|
summarize short-distance rides
|
src/utils.py
|
src/utils.py
|
import collections
import datetime
import stravalib.client
import time
class BaseException(Exception):
pass
class ConfigError(BaseException):
pass
class MyStravaClient(stravalib.client.Client):
API_CALL_PAUSE_SECONDS = 0.5
def get_all_gears(self):
all_activities = self.get_activities()
uniq_gear_ids = filter(None, set(activity.gear_id for activity in all_activities))
gears = []
for gear_id in uniq_gear_ids:
time.sleep(self.API_CALL_PAUSE_SECONDS)
gears.append(self.get_gear(gear_id))
return gears
def get_activities(self, **kwargs):
return list(stravalib.client.Client.get_activities(self, **kwargs))
def get_activities_current_month(self, filter_types=['Ride']):
# get first date of current month
now = datetime.datetime.now()
first_of_month = datetime.datetime(now.year, now.month, 1)
# compile activities since first day of current month
matches = []
activities_list = self.get_activities(after=first_of_month)
for activity in activities_list:
if activity.type in filter_types:
matches.append(activity)
return matches
def batch_set_privacy(self, activity_ids, private=True):
updated_ids = []
for each in activity_ids:
self.update_activity(each, private=private)
time.sleep(self.API_CALL_PAUSE_SECONDS)
updated_ids.append(each)
return updated_ids
def summarize_gear_usage(activity_list):
gear_usage_count_lookup = collections.defaultdict(int)
gear_distance_lookup = collections.defaultdict(float)
for activity in activity_list:
gear_usage_count_lookup[activity.gear_id] += 1
gear_distance_lookup[activity.gear_id] += activity.distance.get_num()
return dict(gear_usage_count_lookup), dict(gear_distance_lookup)
def summarize(activities_list):
summary = {
'distance': 0.0,
'count_public': 0,
'distance_public': 0.0,
'distance_private': 0.0,
'private_ids': [],
'commute_ids': []
}
for activity in activities_list:
summary['distance'] += activity.distance.get_num()
if activity.private:
summary['distance_private'] += activity.distance.get_num()
summary['private_ids'].append(activity.id)
else:
summary['count_public'] += 1
summary['distance_public'] += activity.distance.get_num()
if activity.commute:
summary['commute_ids'].append(activity.id)
# convert to kms
for k in summary:
if k.startswith('distance'):
summary[k] = round(summary[k] / 1000.0, 1)
summary['count_private'] = len(summary['private_ids'])
summary['count_commute'] = len(summary['commute_ids'])
return summary
|
Python
| 0.999999
|
@@ -1930,24 +1930,50 @@
ivities_list
+, short_ride_threshold=5.0
):%0A summa
@@ -2145,16 +2145,47 @@
te_ids':
+ %5B%5D,%0A 'short_rides_ids':
%5B%5D%0A
@@ -2274,32 +2274,88 @@
tance.get_num()%0A
+ activity_distance = activity.distance.get_num()%0A
if activ
@@ -2414,33 +2414,33 @@
+= activity
-.
+_
distance
.get_num()%0A
@@ -2423,34 +2423,24 @@
ity_distance
-.get_num()
%0A
@@ -2588,35 +2588,150 @@
activity
-.distance.get_num()
+_distance%0A%0A if (activity_distance / 1000.0) %3C short_ride_threshold:%0A summary%5B'short_rides_ids'%5D.append(activity.id)%0A
%0A
|
394581407a7788b315da97f870a6dcd0bfe4bd54
|
fix js MIME type
|
src/utils.py
|
src/utils.py
|
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import json
def is_none(target):
return target is None
def is_none_or_empty(target):
return is_none(target) or len(target) == 0
def write_json_output(response, dic):
response_text, content_type = json.dumps(dic), "application/json"
_do_write(response, response_text, content_type)
def write_jsonp_output(response, dic, jsonp_callback):
if is_none_or_empty(jsonp_callback):
write_json_output(response, dic)
else:
response_text, content_type = jsonp_callback + "(" + json.dumps(dic) + ")", "application/x-javascript"
_do_write(response, response_text, content_type)
def _do_write(response, response_text, content_type):
response.headers['Content-Type'] = content_type
response.out.write(response_text)
|
Python
| 0.000512
|
@@ -591,10 +591,8 @@
ion/
-x-
java
|
a83a8a6b086d0cede9a8ca513a706a8d41659ce7
|
Fix league post issue, only check on edit catchup dev
|
src/views.py
|
src/views.py
|
#!/usr/bin/python
#
# Copyright 2011 Friday Film Club. All Rights Reserved.
"""Main views of the Friday Film Club app."""
__author__ = 'adamjmcgrath@gmail.com (Adam McGrath)'
import logging
from operator import itemgetter
import uuid
from google.appengine.api import channel, files, users
from google.appengine.ext import ndb
import auth
import baserequesthandler
import forms
import models
import settings
HOST_URL = 'http://www.fridayfilmclub.com'
class HomePage(baserequesthandler.RequestHandler):
"""Shows the homepage."""
def get(self):
current_question = models.Question.query(models.Question.is_current == True)
q = current_question.get()
question_image = q and q.clue_image_url(size=260)
self.render_template('index.html', {
'current_question': current_question,
'question_image': question_image
})
class Question(baserequesthandler.RequestHandler):
"""Shows the homepage."""
def get(self, question_id):
if question_id:
question = models.Question.get_by_id(int(question_id))
else:
question = models.Question.query(models.Question.is_current == True).get()
logged_in = self.logged_in
# Only admins can view a question before it's posed,
# only logged in users can view the current question.
if ((not question.posed and not users.is_current_user_admin() and not logged_in) or
(question.is_current and not logged_in)):
self.session['original_url'] = self.request.url
return self.redirect('/login')
if logged_in:
user = self.current_user
else:
user = models.AnonymousUser.get(
existing_user_id=self.session.get('anonymous_user'))
user_key = user.put()
self.session['anonymous_user'] = user_key.id()
user_question_id = '%d-%s' % (question.key.id(), user.key.id())
user_question = models.UserQuestion.get_or_insert(
user_question_id,
question=question.key,
user=user.key,
user_is_admin=user.is_admin,
user_is_anonymous=bool(user.is_anonymous)
)
context = {
'user': user,
'user_question': user_question,
'question': question,
}
if question.is_current or settings.DEBUG:
# Add the realtime scores token.
context['channel_token'] = channel.create_channel(user_question_id)
self.render_template('question.html', context)
class Login(baserequesthandler.RequestHandler):
"""Shows the login page."""
def get(self):
self.render_template('login.html', {})
class Register(baserequesthandler.RequestHandler):
"""Shows the registration page."""
def get(self):
form = forms.Registration()
self.render_template('register.html', {
'form': form
})
def post(self):
provider = self.request.get('provider')
form = forms.Registration(self.request.POST)
if form.validate():
# Set the username and invitation in the session and login to the
# auth provider.
self.session['username'] = self.request.get('username')
self.redirect(self.uri_for('auth_login', provider=provider))
else:
self.render_template('register.html', {
'form': form
})
class Profile(baserequesthandler.RequestHandler):
"The user profile page"
def get(self, username):
user = models.User.get_by_username(username)
user_questions = models.UserQuestion.query(
models.UserQuestion.user == user.key).map(
models.UserQuestion.get_profile_dict)
if not user:
self.error(404)
else:
self.render_template('profile.html', {
'user_profile': user,
'user_questions': sorted(user_questions,
key=itemgetter('season', 'week'))
})
class Settings(baserequesthandler.RequestHandler):
"""Shows the Settings page."""
@auth.login_required
def get(self):
user = self.current_user
self.render_template('settings.html', {
'form': forms.User(obj=user, username=user.key.id())
})
@auth.login_required
def post(self):
user = self.current_user
form = forms.User(formdata=self.request.POST)
success = False
if form.validate():
form.populate_obj(user)
user.put()
success = True
self.render_template('settings.html', {
'form': form,
'success': success
})
class Archive(baserequesthandler.RequestHandler):
"""An archive of old questions."""
def get(self):
questions = models.Question.query(models.Question.posed != None,
models.Question.is_current == False)
self.render_template('archive.html', {
'questions': questions
})
class LeaderBoard(baserequesthandler.RequestHandler):
"""The leader board / results page."""
def get(self, league=None):
if league:
league = models.League.get_by_name(league)
self.render_template('leaderboard.html', {
'channel_token': channel.create_channel(str(uuid.uuid4())),
'league': league,
'season': models.Season.get_current()
})
class HighScores(baserequesthandler.RequestHandler):
"""The high scores page."""
def get(self, league=None):
user_question_query = models.UserQuestion.query().order(
-models.UserQuestion.score)
if league:
league = models.League.get_by_name(league)
user_question_query = user_question_query.filter(
models.UserQuestion.user.IN(league.users))
self.render_template('highscores.html', {
'user_questions': user_question_query.fetch(10),
'league': league
})
class HowItWorks(baserequesthandler.RequestHandler):
"""How it works / rules."""
def get(self):
self.render_template('how.html', {})
class League(baserequesthandler.RequestHandler):
@auth.login_required
def get(self, league_id=None):
league = models.League.get_by_name(league_id)
self.render_template('league.html', {
'league': league
})
class AddEditLeague(baserequesthandler.RequestHandler):
"""Add / Edit leagues."""
@auth.login_required
def get(self, league_id=None):
if league_id:
league = models.League.get_by_id(int(league_id))
form = forms.League(obj=league, id=league.key.id())
else:
league = None
form = forms.League()
# Only the owner can edit a league.
if league and league.owner != self.current_user.key:
return self.error(401)
self.render_template('addeditleague.html', {
'form': form,
'league': league,
'success': self.request.get('success')
})
@auth.login_required
def post(self, league_id=None):
if league_id:
league = models.League.get_by_id(int(league_id))
else:
league = models.League()
# Only the owner can edit a league.
if league and league.owner != self.current_user.key:
return self.error(401)
form = forms.League(formdata=self.request.POST, obj=league)
if form.validate():
form.populate_obj(league)
self.redirect('/league/edit/%d?success=true' % league.put().id())
else:
self.render_template('addeditleague.html', {
'form': form,
'league': league
})
|
Python
| 0
|
@@ -6749,32 +6749,35 @@
e.%0A if league
+_id
and league.owne
|
d816e103a6092766398bc74ae2ed844ff3f9598b
|
Handle missing sections
|
pwndbg/commands/elf.py
|
pwndbg/commands/elf.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from elftools.elf.elffile import ELFFile
import gdb
import pwndbg.commands
@pwndbg.commands.Command
def elfheader():
"""
Prints the section mappings contained in the ELF header.
"""
local_path = pwndbg.file.get_file(pwndbg.proc.exe)
with open(local_path, 'rb') as f:
elffile = ELFFile(f)
load_segment = elffile.get_segment(3)
segment_base = load_segment['p_vaddr']
sections = []
for section in elffile.iter_sections():
start = section['sh_addr']
# Don't print sections that aren't mapped into memory
if start == 0:
continue
size = section['sh_size']
sections.append((start, start + size, section.name.decode('ascii')))
sections.sort()
for start, end, name in sections:
print('%#x - %#x %s' % (start, end, name))
@pwndbg.commands.Command
def gotplt():
"""
Prints any symbols found in the .got.plt section if it exists.
"""
print_symbols_in_section('.got.plt', '@got.plt')
@pwndbg.commands.Command
def plt():
"""
Prints any symbols found in the .plt section if it exists.
"""
print_symbols_in_section('.plt', '@plt')
def get_section_bounds(section_name):
section_name = section_name.encode('ascii')
with open(pwndbg.proc.exe, 'rb') as f:
elffile = ELFFile(f)
section = elffile.get_section_by_name(section_name)
start = section['sh_addr']
size = section['sh_size']
return (start, start + size)
def print_symbols_in_section(section_name, filter_text=''):
start, end = get_section_bounds(section_name)
if start == None:
print(pwndbg.color.red('Could not find section'))
return
symbols = get_symbols_in_region(start, end, filter_text)
for symbol, addr in symbols:
print(hex(int(addr)) + ': ' + symbol)
def get_symbols_in_region(start, end, filter_text=''):
symbols = []
ptr_size = pwndbg.typeinfo.pvoid.sizeof
addr = start
while addr < end:
name = pwndbg.symbol.get(addr)
if name != '' and '+' not in name and filter_text in name:
symbols.append((name, addr))
addr += ptr_size
return symbols
|
Python
| 0.000753
|
@@ -1515,24 +1515,82 @@
ction_name)%0A
+%0A if not section:%0A return (None, None)%0A%0A
star
|
9778533d7ee241541deca9614cd5e8660f75607c
|
Create country without code or remove country code raise error
|
openerp/addons/base/res/res_country.py
|
openerp/addons/base/res/res_country.py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# 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 distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
def location_name_search(self, cr, user, name='', args=None, operator='ilike',
context=None, limit=100):
if not args:
args = []
ids = []
if len(name) == 2:
ids = self.search(cr, user, [('code', 'ilike', name)] + args,
limit=limit, context=context)
search_domain = [('name', operator, name)]
if ids: search_domain.append(('id', 'not in', ids))
ids.extend(self.search(cr, user, search_domain + args,
limit=limit, context=context))
locations = self.name_get(cr, user, ids, context)
return sorted(locations, key=lambda (id, name): ids.index(id))
class Country(osv.osv):
_name = 'res.country'
_description = 'Country'
_columns = {
'name': fields.char('Country Name', size=64,
help='The full name of the country.', required=True, translate=True),
'code': fields.char('Country Code', size=2,
help='The ISO country code in two chars.\n'
'You can use this field for quick search.'),
'address_format': fields.text('Address Format', help="""You can state here the usual format to use for the \
addresses belonging to this country.\n\nYou can use the python-style string patern with all the field of the address \
(for example, use '%(street)s' to display the field 'street') plus
\n%(state_name)s: the name of the state
\n%(state_code)s: the code of the state
\n%(country_name)s: the name of the country
\n%(country_code)s: the code of the country"""),
'currency_id': fields.many2one('res.currency', 'Currency'),
}
_sql_constraints = [
('name_uniq', 'unique (name)',
'The name of the country must be unique !'),
('code_uniq', 'unique (code)',
'The code of the country must be unique !')
]
_defaults = {
'address_format': "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s",
}
_order='name'
name_search = location_name_search
def create(self, cursor, user, vals, context=None):
if vals.get('code'):
vals['code'] = vals['code'].upper()
return super(Country, self).create(cursor, user, vals,
context=context)
def write(self, cursor, user, ids, vals, context=None):
if 'code' in vals:
vals['code'] = vals['code'].upper()
return super(Country, self).write(cursor, user, ids, vals,
context=context)
class CountryState(osv.osv):
_description="Country state"
_name = 'res.country.state'
_columns = {
'country_id': fields.many2one('res.country', 'Country',
required=True),
'name': fields.char('State Name', size=64, required=True,
help='Administrative divisions of a country. E.g. Fed. State, Departement, Canton'),
'code': fields.char('State Code', size=3,
help='The state code in max. three chars.', required=True),
}
_order = 'code'
name_search = location_name_search
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Python
| 0.000001
|
@@ -3175,16 +3175,22 @@
t('code'
+,False
):%0A
@@ -3404,22 +3404,30 @@
if
+vals.get(
'code'
- in v
+,F
als
+e)
:%0A
|
6226c17ed1e9313dc202b44fc69b098a09140983
|
fix translation
|
pycket/values_regex.py
|
pycket/values_regex.py
|
from pycket.base import W_Object
from pycket.error import SchemeException
from pycket import values, values_string
from pycket import regexp
from rpython.rlib.rsre import rsre_core
CACHE = regexp.RegexpCache()
class W_AnyRegexp(W_Object):
_immutable_fields_ = ["source"]
errorname = "regexp"
def __init__(self, source):
self.source = source
self.code = None
def ensure_compiled(self):
if self.code is None:
code, flags, groupcount, groupindex, indexgroup, group_offsets = regexp.compile(CACHE, self.source, 0)
self.code = code
self.flags = flags
self.groupcount = groupcount
self.groupindex = groupindex
self.indexgroup = indexgroup
self.group_offsets = group_offsets
def match_string(self, s):
self.ensure_compiled()
endpos = len(s)
ctx = rsre_core.search(self.code, s)
if not ctx:
return None
result = [ctx.group(i) for i in range(self.groupcount + 1)]
return result
def match_port(self, w_port):
max_match = w_port._length_up_to_end()
pos = w_port.tell()
for i in range(max_match):
w_port.seek(pos)
s = w_port.read(i)
result = self.match_string(s)
if result:
return result
return None
def eqv(self, other):
return type(self) is type(other) and \
(self.code == other.code if (self.code or other.code) \
else self.source == other.source)
class W_Regexp(W_AnyRegexp): pass
class W_PRegexp(W_AnyRegexp): pass
class W_ByteRegexp(W_AnyRegexp): pass
class W_BytePRegexp(W_AnyRegexp): pass
|
Python
| 0.000028
|
@@ -1412,22 +1412,90 @@
-return
+if not isinstance(other, W_AnyRegexp):%0A return False%0A if
type(se
@@ -1516,14 +1516,9 @@
her)
- and %5C
+:
%0A
@@ -1526,16 +1526,19 @@
+if
(self.co
@@ -1540,18 +1540,18 @@
lf.code
-==
+or
other.c
@@ -1553,21 +1553,42 @@
her.code
- if (
+):%0A return
self.cod
@@ -1581,34 +1581,34 @@
eturn self.code
-or
+==
other.code) %5C%0A
@@ -1606,11 +1606,8 @@
code
-) %5C
%0A
@@ -1619,16 +1619,40 @@
else
+:%0A return
self.so
@@ -1671,17 +1671,37 @@
r.source
-)
+%0A return False
%0A%0A%0A%0Aclas
|
1b7c2d22bfc7987ab689602652e026a5fd72e551
|
Update PkgDistributionCreator.py
|
MTM_Installer/PkgDistributionCreator.py
|
MTM_Installer/PkgDistributionCreator.py
|
#!/usr/bin/env python
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# *** Drew Coobs <coobs1@illinois.edu> ***
# Modified version of Chris Gerke's PkgDistributionCreator script
# https://github.com/autopkg/cgerke-recipes/blob/master/SharedProcessors/PkgDistributionCreator.py
#
import os.path
import subprocess
import shutil
from glob import glob
from autopkglib import Processor, ProcessorError
__all__ = ["PkgDistributionCreator"]
class PkgDistributionCreator(Processor):
description = ("Bundles together munki pkg installers with MTM onboarding pkg. ")
input_variables = {
"source_file1": {
"required": True,
"description": ("Path to a source file (MyCoolPkg1.pkg) "),
},
"source_file2": {
"required": True,
"description": ("Path to a source file (MyCoolPkg2.pkg) "),
},
"source_file3": {
"required": True,
"description": ("Path to a source file (MyCoolPkg3.pkg) "),
},
"source_file4": {
"required": True,
"description": ("Path to a source file (MyCoolPkg4.pkg) "),
},
"source_file5": {
"required": True,
"description": ("Path to a source file (MyCoolPkg5.pkg) "),
},
"source_file6": {
"required": True,
"description": ("Path to a source file (MyCoolPkg6.pkg) "),
},
"distribution_file": {
"required": True,
"description": ("Destination path of distribution file. "),
},
"package_dir": {
"required": True,
"description": ("Directory containing source pkgs. "),
},
"output_file": {
"required": True,
"description": ("Name of output file. "),
},
}
output_variables = {
}
__doc__ = description
source_path = None
def pkgConvert(self):
if os.path.exists('/usr/bin/productbuild'):
try:
self.output("Found binary %s" % '/usr/bin/productbuild')
except OSError as e:
raise ProcessorError(
"Can't find binary %s: %s" % ('/usr/bin/productbuild', e.strerror))
try:
pbcmd = ["/usr/bin/productbuild",
"--synthesize",
"--package", self.env['source_file1'],
"--package", self.env['source_file2'],
"--package", self.env['source_file3'],
"--package", self.env['source_file4'],
"--package", self.env['source_file5'],
"--package", self.env['source_file6'],
self.env['distribution_file']]
p = subprocess.Popen(pbcmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = p.communicate()
except OSError as e:
raise ProcessorError("Creation of distribution file failed with error code %d: %s"
% (e.errno, e.strerror))
if p.returncode != 0:
raise ProcessorError("Creation of distribution file %s failed: %s"
% (self.env['output_file'], err))
try:
pbcmd = ["/usr/bin/productbuild",
"--distribution", self.env['distribution_file'],
"--package-path", self.env['package_dir'],
self.env['output_file']]
p = subprocess.Popen(pbcmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = p.communicate()
except OSError as e:
raise ProcessorError("cmmac execution failed with error code %d: %s"
% (e.errno, e.strerror))
if p.returncode != 0:
raise ProcessorError("cmmac conversion of %s failed: %s"
% (self.env['output_file'], err))
def main(self):
if os.path.exists(self.env['source_file1']):
try:
self.output("Found %s" % self.env['source_file1'])
except OSError as e:
raise ProcessorError(
"Can't find %s" % (self.env['source_file1'], e.strerror))
if os.path.exists(self.env['source_file2']):
try:
self.output("Found %s" % self.env['source_file2'])
except OSError as e:
raise ProcessorError(
"Can't find %s" % (self.env['source_file2'], e.strerror))
if os.path.exists(self.env['source_file3']):
try:
self.output("Found %s" % self.env['source_file3'])
except OSError as e:
raise ProcessorError(
"Can't find %s" % (self.env['source_file3'], e.strerror))
if os.path.exists(self.env['source_file4']):
try:
self.output("Found %s" % self.env['source_file4'])
except OSError as e:
raise ProcessorError(
"Can't find %s" % (self.env['source_file4'], e.strerror))
if os.path.exists(self.env['source_file5']):
try:
self.output("Found %s" % self.env['source_file5'])
except OSError as e:
raise ProcessorError(
"Can't find %s" % (self.env['source_file5'], e.strerror))
if os.path.exists(self.env['source_file6']):
try:
self.output("Found %s" % self.env['source_file6'])
except OSError as e:
raise ProcessorError(
"Can't find %s" % (self.env['source_file6'], e.strerror))
if os.path.exists(self.env['package_dir']):
try:
self.output("Found %s" % self.env['package_dir'])
self.pkgConvert()
except OSError as e:
raise ProcessorError(
"Can't find %s" % (self.env['package_dir'], e.strerror))
if __name__ == '__main__':
processor = PkgDistributionCreator()
processor.execute_shell()
|
Python
| 0
|
@@ -6115,293 +6115,8 @@
'%5D)%0A
- except OSError as e:%0A raise ProcessorError(%0A %22Can't find %25s%22 %25 (self.env%5B'source_file6'%5D, e.strerror))%0A if os.path.exists(self.env%5B'package_dir'%5D):%0A try:%0A self.output(%22Found %25s%22 %25 self.env%5B'package_dir'%5D)%0A
@@ -6145,16 +6145,16 @@
nvert()%0A
+
@@ -6265,27 +6265,28 @@
lf.env%5B'
-package_dir
+source_file6
'%5D, e.st
|
1069574db36d86745fa4357ff2bc35334883ad86
|
Bump app version to 2019.7.1
|
app/handlers/__init__.py
|
app/handlers/__init__.py
|
__version__ = "2019.7.0"
__versionfull__ = __version__
|
Python
| 0
|
@@ -15,17 +15,17 @@
%222019.7.
-0
+1
%22%0A__vers
|
20d5e52221713ef1ab1bc9cd74b47520bea69ac6
|
Add tasks TODO
|
api/experiments/tasks.py
|
api/experiments/tasks.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
import polyaxon as plx
from api.settings import CeleryTasks
from api.celery_api import app
from experiments.models import Experiment
from experiments.task_status import ExperimentStatus
logger = logging.getLogger('polyaxon.api.experiments')
def get_experiment_run_status(experiment):
job_id, status = ExperimentStatus.get_status(experiment.id)
return {'job_id': job_id, 'status': status}
def start_experiment(experiment):
job_id, status = ExperimentStatus.get_status(experiment.id)
if not status or ExperimentStatus.is_final_status(status):
job = execute.delay(experiment.id)
ExperimentStatus.set_status(experiment.id, job.id, 'PENDING')
return {'status': 'PENDING'}
return {'status': status}
@app.task(name=CeleryTasks.START_EXPERIMENT)
def execute(experiment_id):
try:
experiment = Experiment.objects.get(id=experiment_id)
except Experiment.DoesNotExist:
logger.info('Experiment id `{}` does not exist'.format(experiment_id))
return
plx_xp = plx.experiments.create_experiment(experiment.to_config())
plx_xp.train()
|
Python
| 0.001469
|
@@ -103,32 +103,8 @@
ng%0A%0A
-import polyaxon as plx%0A%0A
from
@@ -263,17 +263,16 @@
Status%0A%0A
-%0A
logger =
@@ -1103,90 +1103,41 @@
-plx_xp = plx.experiments.create_experiment(experiment.to_config())%0A plx_xp.train()
+# TODO: fix me%0A return experiment
%0A
|
6904e4e83556136788dd3ffb18e89830733bf902
|
Use correct attribute for property objects
|
pydispatch/dispatch.py
|
pydispatch/dispatch.py
|
import sys
import weakref
import types
from pydispatch.properties import Property
PY2 = sys.version_info.major == 2
if not PY2:
basestring = str
def get_method_vars(m):
if PY2:
f = m.im_func
obj = m.im_self
else:
f = m.__func__
obj = m.__self__
return f, obj
class WeakMethodContainer(weakref.WeakValueDictionary):
def keys(self):
if PY2:
return self.iterkeys()
return super(WeakMethodContainer, self).keys()
def add_method(self, m):
f, obj = get_method_vars(m)
wrkey = (f, id(obj))
self[wrkey] = obj
def del_method(self, m):
f, obj = get_method_vars(m)
wrkey = (f, id(obj))
if wrkey in self:
del self[wrkey]
def del_instance(self, obj):
to_remove = set()
for wrkey, _obj in self.iter_instances():
if obj is _obj:
to_remove.add(wrkey)
for wrkey in to_remove:
del self[wrkey]
def iter_instances(self):
for wrkey in self.keys():
obj = self.get(wrkey)
if obj is None:
continue
yield wrkey, obj
def iter_methods(self):
for wrkey, obj in self.iter_instances():
f, obj_id = wrkey
yield getattr(obj, f.__name__)
class Event(object):
__slots__ = ('obj', 'name', 'listeners')
def __init__(self, obj, name):
self.obj = obj
self.name = name
self.listeners = WeakMethodContainer()
def add_listener(self, callback):
self.listeners.add_method(callback)
def remove_listener(self, obj):
if isinstance(obj, types.MethodType):
self.listeners.del_method(obj)
else:
self.listeners.del_instance(obj)
def __call__(self, *args, **kwargs):
for m in self.listeners.iter_methods():
r = m(*args, **kwargs)
if r is False:
return r
def __repr__(self):
return '<{}: {}>'.format(self.__class__, self)
def __str__(self):
return self.name
class Dispatcher(object):
def __new__(cls, *args, **kwargs):
def iter_bases(_cls):
if _cls is object:
raise StopIteration
yield _cls
for b in _cls.__bases__:
for _cls_ in iter_bases(b):
yield _cls_
props = {}
events = set()
for _cls in iter_bases(cls):
for attr in dir(_cls):
prop = getattr(_cls, attr)
if attr not in props and isinstance(prop, Property):
props[attr] = prop
prop.name = attr
_events = getattr(_cls, '_events_', [])
events |= set(_events)
cls._PROPERTIES_ = props
cls._EVENTS_ = events
obj = super(Dispatcher, cls).__new__(cls)
obj._Dispatcher__init_events()
return obj
def __del__(self):
if not hasattr(self, '_Dispatcher__property_events'):
return
for prop in self.__property_events.values():
prop._del_instance(self)
def __init_events(self):
if hasattr(self, '_Dispatcher__events'):
return
self.__events = {}
for name in self._EVENTS_:
self.__events[name] = Event(self, name)
self.__property_events = {}
for name, prop in self._PROPERTIES_.items():
self.__property_events[name] = Event(self, name)
prop._add_instance(self)
def register_event(self, *names):
for name in names:
if name in self.__events:
continue
self.__events[name] = Event(self, name)
def bind(self, **kwargs):
props = self.__property_events
events = self.__events
for name, cb in kwargs.items():
if name in props:
e = props[name]
else:
e = events[name]
e.add_listener(cb)
def unbind(self, *args):
for arg in args:
for e in self.__events.values():
e.remove_listener(arg)
def emit(self, name, *args, **kwargs):
e = self.__property_events.get(name)
if e is None:
e = self.__events[name]
return e(*args, **kwargs)
|
Python
| 0.000007
|
@@ -3009,35 +3009,19 @@
, '_
-Dispatcher__property_events
+PROPERTIES_
'):%0A
@@ -3065,32 +3065,27 @@
n self._
-_property_events
+PROPERTIES_
.values(
|
5430c47894c0a43def924a8703259a22f2092c85
|
Change url to confirm_delete
|
api/nodes/serializers.py
|
api/nodes/serializers.py
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, Link, WaterbutlerLink
from website.models import Node
from framework.auth.core import Auth
from rest_framework import exceptions
class NodeSerializer(JSONAPISerializer):
# TODO: If we have to redo this implementation in any of the other serializers, subclass ChoiceField and make it
# handle blank choices properly. Currently DRF ChoiceFields ignore blank options, which is incorrect in this
# instance
category_choices = Node.CATEGORY_MAP.keys()
category_choices_string = ', '.join(["'{}'".format(choice) for choice in category_choices])
filterable_fields = frozenset(['title', 'description', 'public'])
id = ser.CharField(read_only=True, source='_id')
title = ser.CharField(required=True)
description = ser.CharField(required=False, allow_blank=True, allow_null=True)
category = ser.ChoiceField(choices=category_choices, help_text="Choices: " + category_choices_string)
date_created = ser.DateTimeField(read_only=True)
date_modified = ser.DateTimeField(read_only=True)
tags = ser.SerializerMethodField(help_text='A dictionary that contains two lists of tags: '
'user and system. Any tag that a user will define in the UI will be '
'a user tag')
links = LinksField({
'html': 'get_absolute_url',
'children': {
'related': Link('nodes:node-children', kwargs={'node_id': '<pk>'}),
'count': 'get_node_count',
},
'contributors': {
'related': Link('nodes:node-contributors', kwargs={'node_id': '<pk>'}),
'count': 'get_contrib_count',
},
'pointers': {
'related': Link('nodes:node-pointers', kwargs={'node_id': '<pk>'}),
'count': 'get_pointers_count',
},
'registrations': {
'related': Link('nodes:node-registrations', kwargs={'node_id': '<pk>'}),
'count': 'get_registration_count',
},
'files': {
'related': Link('nodes:node-files', kwargs={'node_id': '<pk>'})
},
})
properties = ser.SerializerMethodField(help_text='A dictionary of read-only booleans: registration, collection,'
'and dashboard. Collections are special nodes used by the Project '
'Organizer to, as you would imagine, organize projects. '
'A dashboard is a collection node that serves as the root of '
'Project Organizer collections. Every user will always have '
'one Dashboard')
# TODO: When we have 'admin' permissions, make this writable for admins
public = ser.BooleanField(source='is_public', read_only=True,
help_text='Nodes that are made public will give read-only access '
'to everyone. Private nodes require explicit read '
'permission. Write and admin access are the same for '
'public and private nodes. Administrators on a parent '
'node have implicit read permissions for all child nodes',
)
# TODO: finish me
class Meta:
type_ = 'nodes'
def get_absolute_url(self, obj):
return obj.absolute_url
# TODO: See if we can get the count filters into the filter rather than the serializer.
def get_user_auth(self, request):
user = request.user
if user.is_anonymous():
auth = Auth(None)
else:
auth = Auth(user)
return auth
def get_node_count(self, obj):
auth = self.get_user_auth(self.context['request'])
nodes = [node for node in obj.nodes if node.can_view(auth) and node.primary]
return len(nodes)
def get_contrib_count(self, obj):
return len(obj.contributors)
def get_registration_count(self, obj):
auth = self.get_user_auth(self.context['request'])
registrations = [node for node in obj.node__registrations if node.can_view(auth)]
return len(registrations)
def get_pointers_count(self, obj):
return len(obj.nodes_pointer)
@staticmethod
def get_properties(obj):
ret = {
'registration': obj.is_registration,
'collection': obj.is_folder,
'dashboard': obj.is_dashboard,
}
return ret
@staticmethod
def get_tags(obj):
ret = {
'system': [tag._id for tag in obj.system_tags],
'user': [tag._id for tag in obj.tags],
}
return ret
def create(self, validated_data):
node = Node(**validated_data)
node.save()
return node
def update(self, instance, validated_data):
"""Update instance with the validated data. Requires
the request to be in the serializer context.
"""
assert isinstance(instance, Node), 'instance must be a Node'
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
return instance
class NodeDeleteSerializer(JSONAPISerializer):
node_id = ser.CharField(read_only=True)
warning_message = ser.CharField(read_only=True)
url = ser.CharField(read_only=True, help_text='Use new url to submit DELETE request')
class Meta:
type_ = 'nodes'
class NodePointersSerializer(JSONAPISerializer):
id = ser.CharField(read_only=True, source='_id')
node_id = ser.CharField(source='node._id', help_text='The ID of the node that this pointer points to')
title = ser.CharField(read_only=True, source='node.title', help_text='The title of the node that this pointer '
'points to')
class Meta:
type_ = 'pointers'
links = LinksField({
'html': 'get_absolute_url',
})
def get_absolute_url(self, obj):
pointer_node = Node.load(obj.node._id)
return pointer_node.absolute_url
def create(self, validated_data):
request = self.context['request']
user = request.user
auth = Auth(user)
node = self.context['view'].get_node()
pointer_node = Node.load(validated_data['node']['_id'])
if not pointer_node:
raise exceptions.NotFound('Node not found.')
try:
pointer = node.add_pointer(pointer_node, auth, save=True)
return pointer
except ValueError:
raise exceptions.ValidationError('Pointer to node {} already in list'.format(pointer_node._id))
def update(self, instance, validated_data):
pass
class NodeFilesSerializer(JSONAPISerializer):
id = ser.CharField(read_only=True, source='_id')
provider = ser.CharField(read_only=True)
path = ser.CharField(read_only=True)
item_type = ser.CharField(read_only=True)
name = ser.CharField(read_only=True)
metadata = ser.DictField(read_only=True)
class Meta:
type_ = 'files'
links = LinksField({
'self': WaterbutlerLink(kwargs={'node_id': '<node_id>'}),
'self_methods': 'valid_self_link_methods',
'related': Link('nodes:node-files', kwargs={'node_id': '<node_id>'},
query_kwargs={'path': '<path>', 'provider': '<provider>'}),
})
@staticmethod
def valid_self_link_methods(obj):
return obj['valid_self_link_methods']
def create(self, validated_data):
# TODO
pass
def update(self, instance, validated_data):
# TODO
pass
|
Python
| 0.000001
|
@@ -5681,19 +5681,30 @@
ue)%0A
-url
+confirm_delete
= ser.C
@@ -5743,44 +5743,15 @@
xt='
-Use
new url
- to submit DELETE request
')%0A%0A
|
9e8b6f47f25d4445031e0c996bc8c92ba6da4cd3
|
Remove unnecessary else
|
pygametemplate/core.py
|
pygametemplate/core.py
|
"""Module containing the core functions of pygametemplate."""
import os
import sys
import traceback
from datetime import datetime
import ctypes
import pygame
from pygametemplate.exceptions import CaughtFatalException
TEST = bool(int(os.environ.get("TEST", "0")))
PATH = os.getcwd()
def path_to(*path):
"""Return the complete absolute path of the path given."""
return os.path.join(PATH, *"/".join(path).split("/"))
LOG_FILE = path_to("log.txt")
def log(*error_message, **options):
"""Takes 1 or more variables and concatenates them to create the error message."""
fatal = options.get("fatal", True) # `fatal` option defaults to True
error_message = "".join(map(str, error_message))
with open(LOG_FILE, "a") as log_file:
log_file.write("{} - {}.\n".format(datetime.utcnow(), error_message))
log_file.write(traceback.format_exc() + "\n")
if fatal:
if TEST:
raise # pylint: disable=misplaced-bare-raise
text = ("An error has occurred:\n\n {}.\n\n\n"
"Please check log.txt for details.").format(error_message)
ctypes.windll.user32.MessageBoxW(0, text, "Error", 0)
raise CaughtFatalException(sys.exc_info()[1])
else:
pass # TODO: Add some code here to show an error message in game
# Asset loading
def load_image(image_name, fix_alphas=True, file_extension=".png"):
"""Load the image with the given `image_name` (excluding file extension).
Setting `fix_alphas` to False enables the image to be able to fade.
A different file extension can be specified via the
`file_extension` keyword argument, which defaults to ".png".
"""
# TODO: Add stuff for loading images of the correct resolution
# depending on the player's resolution settings.
image_path = path_to("assets/images", image_name + file_extension)
try:
try:
image = pygame.image.load(image_path)
except pygame.error:
raise IOError
except IOError:
log("Image file not found: ", image_name, file_extension)
if fix_alphas:
return image.convert_alpha() # Fixes per pixel alphas permanently
return image.convert()
def load_font(font_name, font_size, file_extension=".ttf"):
"""Load the font with the given `font_name` with the given `font_size`."""
font_path = path_to("assets/fonts", font_name + file_extension)
try:
return pygame.font.Font(font_path, font_size)
except IOError:
log("Font file not found: ", font_name, file_extension)
|
Python
| 0.000006
|
@@ -1224,30 +1224,9 @@
1%5D)%0A
- else:%0A pass
+%0A
|
c306c3b408e880edfc6d49e31575dc91a31783bd
|
Switch reset command to use call_command instead of subprocess.
|
kive/metadata/management/commands/reset.py
|
kive/metadata/management/commands/reset.py
|
from optparse import make_option
import os
import shutil
import subprocess
import sys
from django.core.management.base import BaseCommand
from django.core.management import call_command
import kive.settings # @UnresolvedImport
class Command(BaseCommand):
help = 'Resets the database and loads sample data.'
option_list = BaseCommand.option_list + (
make_option('--load', '-l', help="fixture name to load"), )
def handle(self, *args, **options):
python = sys.executable
manage_script = sys.argv[0]
fixture = options['load']
targets = ["CodeResources",
"Datasets",
"Logs",
"Sandboxes",
"VerificationLogs",
"VerificationScripts"]
for target in targets:
target_path = os.path.join(kive.settings.MEDIA_ROOT, target)
if os.path.isdir(target_path):
shutil.rmtree(target_path)
subprocess.check_call([python, manage_script, "flush", "--noinput"])
call_command("migrate")
# flush truncates all tables, so we need to re-load this stuff.
call_command("loaddata", "initial_groups")
call_command("loaddata", "initial_user")
call_command("loaddata", "initial_data")
os.mkdir(os.path.join(kive.settings.MEDIA_ROOT, "Sandboxes"))
if fixture:
call_command("loaddata", fixture)
fixture_folder = os.path.join("FixtureFiles", fixture)
if os.path.isdir(fixture_folder):
for child in os.listdir(fixture_folder):
source = os.path.join(fixture_folder, child)
if os.path.isdir(source):
destination = os.path.join(kive.settings.MEDIA_ROOT,
child)
shutil.copytree(source, destination)
|
Python
| 0
|
@@ -53,37 +53,8 @@
util
-%0Aimport subprocess%0Aimport sys
%0A%0Afr
@@ -448,76 +448,8 @@
s):%0A
- python = sys.executable%0A manage_script = sys.argv%5B0%5D%0A
@@ -892,24 +892,16 @@
-
%0A
@@ -905,75 +905,47 @@
-subprocess.check_call(%5Bpython, manage_script, %22flush%22, %22--noinput%22%5D
+call_command(%22flush%22, interactive=False
)%0A
|
e52d0ee26ba4daf01567c460a480afb3a72667ab
|
Fix to pip provider
|
kokki/cookbooks/pip/libraries/providers.py
|
kokki/cookbooks/pip/libraries/providers.py
|
__all__ = ["PipPackageProvider"]
import re
from subprocess import check_call, Popen, PIPE, STDOUT
from kokki import *
from kokki.providers.package import PackageProvider
version_re = re.compile(r'\S\S(.*)\/(.*)-(.*)-py(.*).egg\S')
best_match_re = re.compile(r'Best match: (.*) (.*)\n')
class PipPackageProvider(PackageProvider):
def get_current_status(self):
p = Popen("%s freeze | grep ^%s==" % (self.pip_binary_path, self.resource.package_name), stdout=PIPE, stderr=STDOUT, shell=True)
out = p.communicate()[0]
res = p.wait()
if res != 0:
self.current_version = None
else:
try:
self.current_version = out.split("==", 2)[1]
except IndexError:
raise Fail("pip could not determine installed package version.")
@property
def candidate_version(self):
if not hasattr(self, '_candidate_version'):
if re.match("^[A-Za-z0-9_.-]+$", self.resource.package_name):
p = Popen([self.easy_install_binary_path, "-n", self.resource.package_name], stdout=PIPE, stderr=STDOUT)
out = p.communicate()[0]
res = p.wait()
if res != 0:
self.log.warning("easy_install check returned a non-zero result (%d) %s" % (res, self.resource))
# self._candidate_version = None
# else:
m = best_match_re.search(out)
if not m:
self._candidate_version = None
else:
self._candidate_version = m.group(2)
else:
self._candidate_vesion = self.resource.version
return self._candidate_version
@property
def pip_binary_path(self):
return "pip"
@property
def easy_install_binary_path(self):
return "easy_install"
def install_package(self, name, version):
check_call([self.pip_binary_path, "install", name], stdout=PIPE, stderr=STDOUT)
def update_package(self, name, version):
self.install_package(name, version)
def remove_package(self, name, version):
check_call([self.pip_binary_path, "uninstall", name])
def purge_package(self, name, version):
self.remove_package(name, version)
|
Python
| 0.000001
|
@@ -704,13 +704,21 @@
=%22,
-2
+1
)%5B1%5D
+.strip()
%0A
|
8c26745c0608b2cc49db0e7d186eb3ad8a627bbc
|
Fix a copy-paste error in logging statements
|
examples/demo_receive.py
|
examples/demo_receive.py
|
#!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and
# limitations under the License.
#
# The Original Code is Pika.
#
# The Initial Developers of the Original Code are LShift Ltd, Cohesive
# Financial Technologies LLC, and Rabbit Technologies Ltd. Portions
# created before 22-Nov-2008 00:00:00 GMT by LShift Ltd, Cohesive
# Financial Technologies LLC, or Rabbit Technologies Ltd are Copyright
# (C) 2007-2008 LShift Ltd, Cohesive Financial Technologies LLC, and
# Rabbit Technologies Ltd.
#
# Portions created by LShift Ltd are Copyright (C) 2007-2009 LShift
# Ltd. Portions created by Cohesive Financial Technologies LLC are
# Copyright (C) 2007-2009 Cohesive Financial Technologies
# LLC. Portions created by Rabbit Technologies Ltd are Copyright (C)
# 2007-2009 Rabbit Technologies Ltd.
#
# Portions created by Tony Garnock-Jones are Copyright (C) 2009-2010
# LShift Ltd and Tony Garnock-Jones.
#
# All Rights Reserved.
#
# Contributor(s): ______________________________________.
#
# Alternatively, the contents of this file may be used under the terms
# of the GNU General Public License Version 2 or later (the "GPL"), in
# which case the provisions of the GPL are applicable instead of those
# above. If you wish to allow use of your version of this file only
# under the terms of the GPL, and not to allow others to use your
# version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the
# notice and other provisions required by the GPL. If you do not
# delete the provisions above, a recipient may use your version of
# this file under the terms of any one of the MPL or the GPL.
#
# ***** END LICENSE BLOCK *****
'''
Example of simple consumer. Acks each message as it arrives.
'''
import logging
import sys
import pika
# Import all adapters for easier experimentation
from pika.adapters import *
logging.basicConfig(level=logging.INFO)
connection = None
channel = None
def on_connected(connection):
global channel
logging.info("demo_send: Connected to RabbitMQ")
connection.channel(on_channel_open)
def on_channel_open(channel_):
global channel
channel = channel_
logging.info("demo_send: Received our Channel")
channel.queue_declare(queue="test", durable=True,
exclusive=False, auto_delete=False,
callback=on_queue_declared)
def on_queue_declared(frame):
logging.info("demo_send: Queue Declared")
channel.basic_consume(handle_delivery, queue='test')
def handle_delivery(channel, method, header, body):
logging.info("demo_send.handle_delivery")
logging.info(" method: %r" % method)
logging.info(" header: %r" % header)
logging.info(" body: %r" % body)
channel.basic_ack(delivery_tag=method.delivery_tag)
if __name__ == '__main__':
host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1'
parameters = pika.ConnectionParameters(host)
connection = SelectConnection(parameters, on_connected)
try:
connection.ioloop.start()
except KeyboardInterrupt:
connection.close()
connection.ioloop.start()
|
Python
| 0.000021
|
@@ -2500,20 +2500,23 @@
o(%22demo_
-send
+receive
: Connec
@@ -2671,20 +2671,23 @@
o(%22demo_
-send
+receive
: Receiv
@@ -2928,20 +2928,23 @@
o(%22demo_
-send
+receive
: Queue
@@ -3092,12 +3092,15 @@
emo_
-send
+receive
.han
|
d77e3fbc0d59ca31ce028cc31f5d1e06f08900f4
|
Fix color effect decorator in GoL example (#20)
|
examples/game_of_life.py
|
examples/game_of_life.py
|
from hecate import core
from hecate import seeds
from hecate.core import color_effects
class GameOfLife(core.CellularAutomaton):
""" The Idea of classic CA built with HECATE framework """
state = core.IntegerProperty(max_val=1)
class Topology:
dimensions = 2
lattice = core.OrthogonalLattice()
neighborhood = core.MooreNeighborhood()
border = core.TorusBorder()
def emit(self):
for i in range(len(self.buffers)):
self.buffers[i].state = self.main.state
def absorb(self):
neighbors_alive = core.IntegerVariable()
for i in range(len(self.buffers)):
neighbors_alive += self.neighbors[i].buffer.state
is_born = (8 >> neighbors_alive) & 1
is_sustain = (12 >> neighbors_alive) & 1
self.main.state = is_born | is_sustain & self.main.state
@color_effects.moving_average
def color(self):
r = self.main.state * 255
g = self.main.state * 255
b = self.main.state * 255
return (r, g, b)
class GameOfLifeStatic(GameOfLife):
class Topology:
dimensions = 2
lattice = core.OrthogonalLattice()
neighborhood = core.MooreNeighborhood()
border = core.StaticBorder(1)
class GOLExperiment(core.Experiment):
""" Particular experiment, to be loaded at runtime in future """
word = "HECATE FIRST EXPERIMENT"
size = (640, 360, )
zoom = 3
pos = [0, 0]
seed = seeds.patterns.BigBang(
pos=(320, 180),
size=(100, 100),
vals={
"state": seeds.random.RandInt(0, 1),
}
)
class GOLExperiment2(core.Experiment):
""" Experiment initialized with Primordial Soup pattern. """
word = "HECATE FIRST EXPERIMENT"
size = (640, 360, )
zoom = 3
pos = [0, 0]
seed = seeds.patterns.PrimordialSoup(
vals={
"state": seeds.random.RandInt(0, 1),
}
)
if __name__ == "__main__":
import moire
ca = GameOfLife(GOLExperiment)
gui = moire.GUI(runnable=ca)
gui.run()
|
Python
| 0
|
@@ -878,16 +878,15 @@
cts.
-m
+M
oving
-_a
+A
vera
|
cf77fca59a9073edfab27fd30e907a3054f1ffaa
|
Add setting for trusting X-Forwarded-Host header in Django
|
kerrokantasi/settings/base.py
|
kerrokantasi/settings/base.py
|
import os
import environ
import raven
gettext = lambda s: s
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
root = environ.Path(BASE_DIR)
env = environ.Env()
env = environ.Env(
DEBUG=(bool, False),
SECRET_KEY=(str, ''),
ALLOWED_HOSTS=(list, []),
ADMINS=(list, []),
DATABASE_URL=(str, 'postgis:///kerrokantasi'),
JWT_SECRET_KEY=(str, ''),
JWT_AUDIENCE=(str, ''),
MEDIA_ROOT=(environ.Path(), root('media')),
STATIC_ROOT=(environ.Path(), root('static')),
MEDIA_URL=(str, '/media/'),
STATIC_URL=(str, '/static/'),
SENTRY_DSN=(str, ''),
SENTRY_ENVIRONMENT=(str,''),
COOKIE_PREFIX=(str, 'kerrokantasi'),
DEMOCRACY_UI_BASE_URL=(str, 'http://localhost:8086'),
)
DEBUG = env('DEBUG')
SECRET_KEY = env('SECRET_KEY')
ALLOWED_HOSTS = env('ALLOWED_HOSTS')
ADMINS = env('ADMINS')
DATABASES = {
'default': env.db('DATABASE_URL')
}
JWT_AUTH = {
'JWT_SECRET_KEY': env('JWT_SECRET_KEY'),
'JWT_AUDIENCE': env('JWT_AUDIENCE')
}
MEDIA_ROOT = env('MEDIA_ROOT')
MEDIA_URL = env('MEDIA_URL')
STATIC_ROOT = env('STATIC_ROOT')
STATIC_URL = env('STATIC_URL')
SENTRY_DSN = env('SENTRY_DSN')
RAVEN_CONFIG = {
'dsn': env('SENTRY_DSN'),
'environment': env('SENTRY_ENVIRONMENT'),
'release': raven.fetch_git_sha(BASE_DIR),
}
CSRF_COOKIE_NAME = '{}-csrftoken'.format(env('COOKIE_PREFIX'))
SESSION_COOKIE_NAME = '{}-sessionid'.format(env('COOKIE_PREFIX'))
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_PATH = '/{}'.format(env('COOKIE_PREFIX'))
DEMOCRACY_UI_BASE_URL = env('DEMOCRACY_UI_BASE_URL')
### Settings below do not usually need changing
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'modeltranslation',
'mptt',
'nested_admin',
'rest_framework',
'reversion',
'corsheaders',
'easy_thumbnails',
'rest_framework_nested',
'djgeojson',
'leaflet',
'ckeditor',
'ckeditor_uploader',
'helusers',
'munigeo',
'kerrokantasi', # User model is project-wide
'democracy', # Reusable participatory democracy app
'parler',
'django_filters',
]
if RAVEN_CONFIG['dsn']:
INSTALLED_APPS.append('raven.contrib.django.raven_compat')
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
]
ROOT_URLCONF = 'kerrokantasi.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'kerrokantasi.wsgi.application'
LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
AUTH_USER_MODEL = 'kerrokantasi.User'
LANGUAGES = (
('fi', gettext('Finnish')),
('sv', gettext('Swedish')),
('en', gettext('English')),
)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/[a-z0-9-]*/?v1/.*$'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'helusers.jwt.JWTAuthentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'],
'DEFAULT_VERSION': '1',
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
JWT_AUTH['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = 'helusers.jwt.get_user_id_from_payload_handler'
DEMOCRACY_PLUGINS = {
"mapdon-hkr": "democracy.plugins.Plugin", # TODO: Create an actual class for this once we know the data format
"mapdon-ksv": "democracy.plugins.Plugin",
"mapdon-ksv-visualize": "democracy.plugins.Plugin",
"map-bikeracks": "democracy.plugins.Plugin",
"map-winterbiking": "democracy.plugins.Plugin"
}
PARLER_DEFAULT_LANGUAGE_CODE = 'en'
PARLER_LANGUAGES = {
None: (
{'code': 'en', },
{'code': 'fi', },
{'code': 'sv', },
),
'default': {
'hide_untranslated': False,
'fallbacks': ['fi', 'en', 'sv'],
}
}
PARLER_ENABLE_CACHING = False
DETECT_LANGS_MIN_PROBA = 0.3
# CKEDITOR_CONFIGS is in __init__.py
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = 'pillow'
# Image files should not exceed 1MB (SI)
MAX_IMAGE_SIZE = 10**6
|
Python
| 0
|
@@ -750,16 +750,58 @@
8086'),%0A
+ TRUST_X_FORWARDED_HOST=(bool, False),%0A
)%0A%0ADEBUG
@@ -1633,16 +1633,71 @@
E_URL')%0A
+%0AUSE_X_FORWARDED_HOST = env('TRUST_X_FORWARDED_HOST')%0A%0A
### Sett
|
54682633b6312cb942d819be9c02beb2b5ad7bef
|
Add edit-entry, single-entry, new_entry.
|
learning_journal/learning_journal/views.py
|
learning_journal/learning_journal/views.py
|
from pyramid.response import Response
import os
HERE = os.path.dirname(__file__)
def home_page(request):
imported_text = open(os.path.join(HERE + '/static/', 'index.html')).read()
return Response(imported_text)
def includeme(config):
config.add_view(home_page, route_name='home')
|
Python
| 0
|
@@ -226,77 +226,682 @@
def
-includeme(config):%0A config.add_view(home_page, route_name='home')%0A
+view_entry(request):%0A imported_text = open(os.path.join(HERE + '/static/', 'single-entry.html')).read()%0A return Response(imported_text)%0A%0A%0Adef new_entry(request):%0A imported_text = open(os.path.join(HERE + '/static/', 'new-entry.html')).read()%0A return Response(imported_text)%0A%0A%0Adef edit_entry(request):%0A imported_text = open(os.path.join(HERE + '/static/', 'edit-entry.html')).read()%0A return Response(imported_text)%0A%0A%0Adef includeme(config):%0A config.add_view(home_page, route_name='home')%0A config.add_view(view_entry, route_name='single-entry')%0A config.add_view(new_entry, route_name='new-entry')%0A config.add_view(edit_entry, route_name='edit-entry')%0A
|
f33ce12f1f4bd53cbaa22d7942c32e82f8b718e9
|
Add an export version tag and encode strings as utf-8.
|
king_phisher/client/export.py
|
king_phisher/client/export.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/client/export.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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 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" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 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 IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import csv
import datetime
import xml.etree.ElementTree as ET
def campaign_to_xml(rpc, campaign_id, xml_file):
root = ET.Element('kingphisher')
# generate export metadata
metadata = ET.SubElement(root, 'metadata')
timestamp = ET.SubElement(metadata, 'timestamp')
timestamp.text = datetime.datetime.now().isoformat()
campaign = ET.SubElement(root, 'campaign')
campaign_info = rpc.remote_table_row('campaigns', campaign_id)
for key, value in campaign_info.items():
ET.SubElement(campaign, key).text = str(value)
# Tables with a campaign_id field
for table_name in ['messages', 'visits', 'credentials', 'deaddrop_deployments', 'deaddrop_connections']:
table_element = ET.SubElement(campaign, table_name)
for table_row in rpc.remote_table('campaign/' + table_name, campaign_id):
table_row_element = ET.SubElement(table_element, table_name[:-1])
for key, value in table_row.items():
ET.SubElement(table_row_element, key).text = str(value)
element_tree = ET.ElementTree(root)
element_tree.write(xml_file, encoding = 'utf-8', xml_declaration = True)
def treeview_liststore_to_csv(treeview, target_file):
target_file_h = open(target_file, 'wb')
writer = csv.writer(target_file_h, quoting = csv.QUOTE_ALL)
column_names = map(lambda x: x.get_property('title'), treeview.get_columns())
column_count = len(column_names)
writer.writerow(column_names)
store = treeview.get_model()
store_iter = store.get_iter_first()
rows_written = 0
while store_iter:
values = map(lambda x: store.get_value(store_iter, x), range(column_count))
writer.writerow(values)
rows_written += 1
store_iter = store.iter_next(store_iter)
target_file_h.close()
return rows_written
|
Python
| 0
|
@@ -1889,16 +1889,84 @@
format()
+%0A%09version = ET.SubElement(metadata, 'version')%0A%09version.text = '1.0'
%0A%0A%09campa
@@ -2157,16 +2157,32 @@
r(value)
+.encode('utf-8')
%0A%0A%09# Tab
@@ -2614,16 +2614,32 @@
r(value)
+.encode('utf-8')
%0A%0A%09eleme
|
d59b01bc8156819b4c19374b79b244968f1043e1
|
Fix location field typo when creating user
|
examples/parent_child.py
|
examples/parent_child.py
|
"""
Complex data model example modeling stackoverflow-like data.
It is used to showcase several key features of elasticsearch-dsl:
* Object and Nested fields: see User and Comment classes and fields they
are used in
* method add_comment is used to add comments
* Parent/Child relationship
* See the Join field on Post creating the relationship between Question
and Answer
* Meta.matches allows the hits from same index to be wrapped in proper
classes
* to see how child objects are created see Question.add_answer
* Question.search_answers shows how to query for children of a
particular parent
"""
from datetime import datetime
from elasticsearch_dsl import Document, Date, Text, Keyword, Boolean, InnerDoc, \
Nested, Object, Join, Long, connections
class User(InnerDoc):
"""
Class used to represent a denormalized user stored on other objects.
"""
id = Long(required=True)
signed_up = Date()
username = Text(fields={'keyword': Keyword()}, required=True)
email = Text(fields={'keyword': Keyword()})
location = Text(fields={'keyword': Keyword()})
class Comment(InnerDoc):
"""
Class wrapper for nested comment objects.
"""
author = Object(User, required=True)
created = Date(required=True)
content = Text(required=True)
class Post(Document):
"""
Base class for Question and Answer containing the common fields.
"""
author = Object(User, required=True)
created = Date(required=True)
body = Text(required=True)
comments = Nested(Comment)
question_answer = Join(relations={'question': 'answer'})
@classmethod
def _matches(cls, hit):
# Post is an abstract class, make sure it never gets used for
# deserialization
return False
class Index:
name = 'test-qa-site'
settings = {
"number_of_shards": 1,
"number_of_replicas": 0,
}
def add_comment(self, user, content, created=None, commit=True):
c = Comment(
author=user,
content=content,
created=created or datetime.now()
)
self.comments.append(c)
if commit:
self.save()
return c
def save(self, **kwargs):
# if there is no date, use now
if self.created is None:
self.created = datetime.now()
return super(Post, self).save(**kwargs)
class Question(Post):
# use multi True so that .tags will return empty list if not present
tags = Keyword(multi=True)
title = Text(fields={'keyword': Keyword()})
@classmethod
def _matches(cls, hit):
" Use Question class for parent documents "
return hit['_source']['question_answer'] == 'question'
@classmethod
def search(cls, **kwargs):
return cls._index.search(**kwargs).filter('term', question_answer='question')
def add_answer(self, user, body, created=None, accepted=False, commit=True):
answer = Answer(
# required make sure the answer is stored in the same shard
_routing=self.meta.id,
# since we don't have explicit index, ensure same index as self
_index=self.meta.index,
# set up the parent/child mapping
question_answer={'name': 'answer', 'parent': self.meta.id},
# pass in the field values
author=user,
created=created,
body=body,
accepted=accepted
)
if commit:
answer.save()
return answer
def search_answers(self):
# search only our index
s = Answer.search()
# filter for answers belonging to us
s = s.filter('parent_id', type="answer", id=self.meta.id)
# add routing to only go to specific shard
s = s.params(routing=self.meta.id)
return s
def get_answers(self):
"""
Get answers either from inner_hits already present or by searching
elasticsearch.
"""
if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits:
return self.meta.inner_hits.answer.hits
return list(self.search_answers())
def save(self, **kwargs):
self.question_answer = 'question'
return super(Question, self).save(**kwargs)
class Answer(Post):
is_accepted = Boolean()
@classmethod
def _matches(cls, hit):
" Use Answer class for child documents with child name 'answer' "
return isinstance(hit['_source']['question_answer'], dict) \
and hit['_source']['question_answer'].get('name') == 'answer'
@classmethod
def search(cls, **kwargs):
return cls._index.search(**kwargs).exclude('term', question_answer='question')
@property
def question(self):
# cache question in self.meta
# any attributes set on self would be interpretted as fields
if 'question' not in self.meta:
self.meta.question = Question.get(
id=self.question_answer.parent, index=self.meta.index)
return self.meta.question
def save(self, **kwargs):
# set routing to parents id automatically
self.meta.routing = self.question_answer.parent
return super(Answer, self).save(**kwargs)
def setup():
" Create an IndexTemplate and save it into elasticsearch. "
index_template = Post._index.as_template('base')
index_template.save()
if __name__ == '__main__':
# initiate the default connection to elasticsearch
connections.create_connection()
# create index
setup()
# user objects to use
nick = User(id=47, signed_up=datetime(2017, 4, 3), username='fxdgear',
email='nick.lang@elastic.co', localtion='Colorado')
honza = User(id=42, signed_up=datetime(2013, 4, 3), username='honzakral',
email='honza@elastic.co', localtion='Prague')
# create a question object
question = Question(
_id=1,
author=nick,
tags=['elasticsearch', 'python'],
title='How do I use elasticsearch from Python?',
body='''
I want to use elasticsearch, how do I do it from Python?
''',
)
question.save()
answer = question.add_answer(honza, "Just use `elasticsearch-py`!")
|
Python
| 0.000001
|
@@ -5806,25 +5806,24 @@
ic.co', loca
-l
tion='Colora
@@ -5952,17 +5952,16 @@
o', loca
-l
tion='Pr
|
7bb5238408d56a2b8491af8c389ef4b739f4ab54
|
Improve archive help text
|
dog/ext/message_logging.py
|
dog/ext/message_logging.py
|
import datetime
import functools
import json
import logging
import re
import discord
from discord.ext import commands
from dog import Cog
from dog.core import checks, converters, utils
logger = logging.getLogger(__name__)
def require_logging_enabled(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
# do not log dms
if not args[1].guild:
return
# args[0] = self, args[1] = msg
if not await args[0].bot.redis.exists(f'message_logging:{args[1].guild.id}:enabled'):
return
# don't log ourselves
if args[1].author == args[0].bot.user:
return
return await func(*args, **kwargs)
return wrapper
def format_record(r, cmd_flags):
"""
Formats a messages row.
"""
flags = {'E': r['edited'], 'D': r['deleted']}
# render the flags
flags_rendered = ''.join(fl for fl, value in flags.items() if value)
# empty out of we are hiding flags, else pad it out
flags_rendered = '' if 'hide-flags' in cmd_flags else f'{flags_rendered: <{len(flags)}} '
# decide which content to show
content = r['new_content'] or r['original_content']
# override on show-original
if 'show-original' in cmd_flags:
content = r['original_content']
# truncate
content = utils.truncate(content, 1500)
created_at = '' if 'hide-dates' in cmd_flags else f'{r["created_at"].strftime("%y-%m-%d %H:%M")} '
message_id = f"{r['message_id']} " if 'show-ids' in cmd_flags else ''
attachments = f" {r['attachments']}" if 'show-attachments' in cmd_flags else ''
return f'{flags_rendered}{message_id}{created_at}{content}{attachments}'
def attachment_to_dict(attachment):
return {
'id': attachment.id,
'size': attachment.size,
'filename': attachment.filename,
'height': attachment.height,
'width': attachment.width,
'url': attachment.url,
'proxy_url': attachment.proxy_url
}
def postprocess_message_content(content):
return utils.prevent_codeblock_breakout(content.replace('\x00', ''))
class MessageLogging(Cog):
@require_logging_enabled
async def on_message(self, msg):
async with self.bot.pgpool.acquire() as conn:
insertion_sql = """
INSERT INTO messages (message_id, guild_id, channel_id, author_id, original_content, new_content,
attachments, deleted, edited, deleted_at, edited_at, created_at)
VALUES ($1, $2, $3, $4, $5, '', $6, FALSE, FALSE, NULL, NULL, $7);
"""
encoded_attachments = json.dumps([attachment_to_dict(tch) for tch in msg.attachments])
content = postprocess_message_content(msg.content)
await conn.execute(insertion_sql, msg.id, msg.guild.id, msg.channel.id, msg.author.id, content,
encoded_attachments, msg.created_at)
@require_logging_enabled
async def on_message_edit(self, before, after):
async with self.bot.pgpool.acquire() as conn:
update_sql = """
UPDATE messages SET edited = TRUE, new_content = $1, edited_at = $3 WHERE message_id = $2
"""
content = postprocess_message_content(after.content)
await conn.execute(update_sql, content, before.id, datetime.datetime.utcnow())
@require_logging_enabled
async def on_message_delete(self, msg):
async with self.bot.pgpool.acquire() as conn:
delete_sql = """
UPDATE messages SET deleted = TRUE, deleted_at = $2 WHERE message_id = $1
"""
await conn.execute(delete_sql, msg.id, datetime.datetime.utcnow())
@commands.command()
@checks.is_moderator()
async def archive(self, ctx, user: discord.User, amount: int, *, flags: converters.Flags={}):
""" Fetches logged messages from a user. """
async with ctx.acquire() as conn:
fetch_sql = """
SELECT * FROM messages WHERE author_id = $1 AND guild_id = $2 ORDER BY created_at DESC LIMIT $3
"""
messages = await conn.fetch(fetch_sql, user.id, ctx.guild.id, amount)
paginator = commands.Paginator()
flag_processors = {
'has-attachments': lambda value, msg: json.loads(msg['attachments']),
'contains': lambda value, msg: value in msg,
'edited': lambda value, msg: msg['edited'],
'deleted': lambda value, msg: msg['deleted'],
'channel': lambda value, msg: msg['channel_id'] == int(value),
'mentions': lambda value, msg: re.search(f'<@!?{value}>', content) is None
}
# add messages
for msg in messages:
content = msg['new_content'] or msg['original_content']
failed_flags = False
for flag_name, processor in flag_processors.items():
if flag_name in flags and not processor(flags[flag_name], msg):
failed_flags = True
if not failed_flags:
paginator.add_line(format_record(msg, flags))
# send pages
if not paginator.pages:
return await ctx.send('```No results.```')
for page in paginator.pages:
await ctx.send(page)
@archive.error
async def archive_error(self, ctx, err):
original = None if not isinstance(err, commands.CommandInvokeError) else err.original
if isinstance(original, ValueError):
await ctx.send('Invalid flag value provided.')
err.should_suppress = True
@commands.command()
@commands.has_permissions(manage_messages=True)
@checks.is_supporter_check()
async def logging(self, ctx, enable: bool):
"""
Toggles logging in this server.
Requires Dogbot supporter and Manage Messages.
"""
key = f'message_logging:{ctx.guild.id}:enabled'
if enable:
await ctx.bot.redis.set(key, 'true')
else:
await ctx.bot.redis.delete(key)
await ctx.ok()
def setup(bot):
bot.add_cog(MessageLogging(bot))
|
Python
| 0.000818
|
@@ -3871,16 +3871,24 @@
%22%22%22
+%0A
Fetches
@@ -3916,16 +3916,444 @@
a user.
+%0A%0A Only Dogbot Moderators can do this.%0A%0A The amount you specify is not equal to the amount of messages that will be shown to you.%0A Rather, it will be the amount of messages that are fetched from the bot's database.%0A%0A Flags allow you to specify which messages you want to see, or how you want to see them.%0A For more information, see https://github.com/slice/dogbot/wiki/Message-Logging.%0A
%22%22%22%0A
|
1e07b574a36e205a9ec16d8b1039089b7fe6b6db
|
Add doc for PWSCF.
|
pymatgen/io/pwscfio.py
|
pymatgen/io/pwscfio.py
|
# coding: utf-8
from __future__ import division, unicode_literals
"""
This module implements input and output processing from PWSCF.
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Virtual Lab"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "ongsp@ucsd.edu"
__date__ = "3/27/15"
import six
class PWInput(object):
"""
Base input file class. Right now, only supports no symmetry and is
very basic.
"""
def __init__(self, structure, pseudo, control=None, system=None, electrons=None,
ions=None, cell=None, kpoints_mode="automatic",
kpoints_grid=(1, 1, 1),kpoints_shift=(0, 0, 0)):
self.structure = structure
sections = {}
sections["control"] = control or {"calculation": "scf"}
sections["system"] = system or {}
sections["electrons"] = electrons or {}
sections["ions"] = ions or {}
sections["cell"] = cell or {}
for species in self.structure.composition.keys():
if species.symbol not in pseudo:
raise PWInputError("Missing %s in pseudo specification!")
self.pseudo = pseudo
self.sections = sections
self.kpoints_mode = kpoints_mode
self.kpoints_grid = kpoints_grid
self.kpoints_shift = kpoints_shift
def __str__(self):
out = []
def to_str(v):
if isinstance(v, six.string_types):
return "'%s'" % v
return v
for k1 in ["control", "system", "electrons", "ions", "cell"]:
v1 = self.sections[k1]
out.append("&%s" % k1.upper())
sub = []
for k2 in sorted(v1.keys()):
sub.append(" %s = %s" % (k2, to_str(v1[k2])))
if k1 == "system":
sub.append(" ibrav = 0")
sub.append(" nat = %d" % len(self.structure))
sub.append(" ntyp = %d" % len(self.structure.composition))
sub.append("/")
out.append(",\n".join(sub))
out.append("ATOMIC_SPECIES")
for k, v in self.structure.composition.items():
out.append(" %s %.4f %s" % (k.symbol, k.atomic_mass,
self.pseudo[k.symbol]))
out.append("ATOMIC_POSITIONS crystal")
for site in self.structure:
out.append(" %s %.6f %.6f %.6f" % (site.specie.symbol, site.a,
site.b, site.c))
out.append("K_POINTS %s" % self.kpoints_mode)
kpt_str = ["%s" % i for i in self.kpoints_grid]
kpt_str.extend(["%s" % i for i in self.kpoints_shift])
out.append(" %s" % " ".join(kpt_str))
out.append("CELL_PARAMETERS angstrom")
for vec in self.structure.lattice.matrix:
out.append(" %f %f %f" % (vec[0], vec[1], vec[2]))
return "\n".join(out)
def write_file(self, filename):
with open(filename, "w") as f:
f.write(self.__str__())
class PWInputError(BaseException):
pass
if __name__ == "__main__":
from pymatgen.core.structure import Structure
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
lattice = [[3.8401979337, 0.00, 0.00],
[1.9200989668, 3.3257101909, 0.00],
[0.00, -2.2171384943, 3.1355090603]]
structure = Structure(lattice, ["Si", "Si"], coords)
pw = PWInput(structure,
control={"calculation": "scf", "pseudo_dir": './'},
pseudo={"Si": "Si.pbe-n-kjpaw_psl.0.1.UPF"},
system={"ecutwfc": 50})
pw.write_file("Si.pw.in")
|
Python
| 0.000028
|
@@ -541,155 +541,1350 @@
one,
- electrons=None,%0A ions=None, cell=None, kpoints_mode=%22automatic%22,%0A kpoints_grid=(1, 1, 1),kpoints_shift=(0, 0, 0)):
+%0A electrons=None, ions=None, cell=None, kpoints_mode=%22automatic%22,%0A kpoints_grid=(1, 1, 1),kpoints_shift=(0, 0, 0)):%0A %22%22%22%0A Initializes a PWSCF input file.%0A%0A Args:%0A structure (Structure): Input structure%0A pseudo (dict): A dict of the pseudopotentials to use.%0A control (dict): Control parameters. Refer to official PWSCF doc%0A on supported parameters. Default to %7B%22calculation%22: %22scf%22%7D%0A system (dict): System parameters. Refer to official PWSCF doc%0A on supported parameters. Default to None, which means %7B%7D.%0A electrons (dict): Electron parameters. Refer to official PWSCF doc%0A on supported parameters. Default to None, which means %7B%7D.%0A ions (dict): Ions parameters. Refer to official PWSCF doc%0A on supported parameters. Default to None, which means %7B%7D.%0A cell (dict): Cell parameters. Refer to official PWSCF doc%0A on supported parameters. Default to None, which means %7B%7D.%0A kpoints_mode (str): Kpoints generation mode. Default to automatic.%0A kpoints_grid (sequence): The kpoint grid. Default to (1, 1, 1).%0A kpoints_shift (sequence): The shift for the kpoints. Defaults to%0A (0, 0, 0).%0A %22%22%22
%0A
@@ -4148,16 +4148,153 @@
ename):%0A
+ %22%22%22%0A Write the PWSCF input file.%0A%0A Args:%0A filename (str): The string filename to output to.%0A %22%22%22%0A
|
e3e878ddfb95141b19bdae9e3713690759149ce1
|
remove unused property
|
pyscreenshot/loader.py
|
pyscreenshot/loader.py
|
import logging
from pyscreenshot import plugins
import traceback
log = logging.getLogger(__name__)
class FailedBackendError(Exception):
pass
class Loader(object):
def __init__(self):
self.plugins = dict()
self.all_names = [x.name for x in self.plugin_classes()]
self.changed = True
self._force_backend = None
self.preference = []
self.default_preference = plugins.default_preference
self._backend = None
def plugin_classes(self):
return plugins.BACKENDS
def set_preference(self, x):
self.changed = True
self.preference = x
def force(self, name):
log.debug('forcing:' + str(name))
self.changed = True
self._force_backend = name
@property
def is_forced(self):
return self._force_backend is not None
@property
def loaded_plugins(self):
return self.plugins.values()
def get_valid_plugin_by_name(self, name):
if name not in self.plugins:
ls = filter(lambda x: x.name == name, self.plugin_classes())
ls = list(ls)
if len(ls):
try:
plugin = ls[0]()
except Exception:
log.debug(traceback.format_exc())
plugin = None
else:
plugin = None
self.plugins[name] = plugin
return self.plugins[name]
def get_valid_plugin_by_list(self, ls):
for name in ls:
x = self.get_valid_plugin_by_name(name)
if x:
return x
def selected(self):
if self.changed:
if self.is_forced:
b = self.get_valid_plugin_by_name(self._force_backend)
if not b:
raise FailedBackendError(
'Forced backend not found, or cannot be loaded:' + self._force_backend)
else:
biglist = self.preference + \
self.default_preference + self.all_names
b = self.get_valid_plugin_by_list(biglist)
if not b:
self.raise_exc()
self.changed = False
self._backend = b
log.debug('selecting plugin:' + self._backend.name)
return self._backend
def raise_exc(self):
message = 'Install at least one backend!'
raise FailedBackendError(message)
|
Python
| 0.000001
|
@@ -840,24 +840,26 @@
s not None%0A%0A
+#
@propert
@@ -852,32 +852,34 @@
# @property%0A
+#
def loaded_p
@@ -884,32 +884,34 @@
_plugins(self):%0A
+#
return s
|
7da9a772771b1734a275107a629ce89b4fb4820d
|
remove verbose debugging stuff from log.
|
pytest_nodev/plugin.py
|
pytest_nodev/plugin.py
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015-2016 Alessandro Amici
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# python 2 support via python-future
from __future__ import absolute_import, unicode_literals
from builtins import dict, zip
import collections
import logging
import os
import sys
import pytest
from . import collect
from . import utils
def pytest_addoption(parser):
group = parser.getgroup('wish')
group.addoption(
'--wish-from-stdlib', action='store_true',
help="Collects objects form the Python standard library.")
group.addoption(
'--wish-from-installed', action='store_true',
help="Collects objects form all installed packages.")
group.addoption(
'--wish-from-all', action='store_true',
help="Collects objects form the Python standard library and all installed packages.")
group.addoption(
'--wish-from-specs', default=[], nargs='+',
help="Collects objects from installed packages. Space separated list of ``pip`` specs.")
group.addoption(
'--wish-from-modules', default=[], nargs='+',
help="Collects objects from installed modules. Space separated list of module names.")
group.addoption(
'--wish-includes', nargs='+',
help="Space separated list of regexs matching full object names to include, "
"defaults to include all objects collected via ``--wish-from-*``.")
group.addoption(
'--wish-excludes', default=[collect.INTERNAL_USE_PATTERN], nargs='+',
help="Space separated list of regexs matching full object names to exclude, "
"defaults to match 'internal use' names %r" % collect.INTERNAL_USE_PATTERN)
group.addoption(
'--wish-predicate', default='builtins:callable',
help="Full name of the predicate passed to ``inspect.getmembers``, "
"defaults to ``builtins.callable``.")
group.addoption('--wish-fail', action='store_true', help="Show wish failures.")
def wish_ensuresession(config):
if hasattr(config, '_wish_index_items'):
return
from_installed = config.getoption('wish_from_installed') or config.getoption('wish_from_all')
if from_installed and os.environ.get('PYTEST_NODEV_MODE') != 'FEARLESS':
raise ValueError("Use of --wish-from-installed/all may be very dangerous, see the docs.")
# take over collect logging
collect.logger.propagate = False
collect.logger.setLevel(logging.DEBUG) # FIXME: loglevel should be configurable
collect.logger.addHandler(utils.EmitHandler(config._warn))
# build the object index
distributions = collections.OrderedDict()
if config.getoption('wish_from_stdlib') or config.getoption('wish_from_all'):
distributions.update(collect.collect_stdlib_distributions())
if from_installed:
distributions.update(collect.collect_installed_distributions())
distributions.update(collect.collect_distributions(config.getoption('wish_from_specs')))
if config.getoption('wish_from_modules'):
distributions['unknown distribution'] = config.getoption('wish_from_modules')
imported_module_names = collect.import_distributions(distributions.items())
wish_includes = config.getoption('wish_includes') or imported_module_names
wish_excludes = config.getoption('wish_excludes')
wish_predicate = config.getoption('wish_predicate')
config._warn('%r' % locals())
# NOTE: 'copy' is needed here because indexing may unexpectedly trigger a module load
modules = sys.modules.copy()
object_index = dict(
collect.generate_objects_from_modules(modules, wish_includes, wish_excludes,
wish_predicate)
)
# store options
config._wish_index_items = list(zip(*sorted(object_index.items()))) or [(), ()]
# delegate interrupting hanging tests to pytest-timeout
os.environ['PYTEST_TIMEOUT'] = os.environ.get('PYTEST_TIMEOUT', '1')
def pytest_generate_tests(metafunc):
if 'wish' not in metafunc.fixturenames:
return
config = metafunc.config
wish_ensuresession(config)
ids, params = config._wish_index_items
metafunc.parametrize('wish', params, ids=ids, scope='module')
if not config.getoption('wish_fail'):
metafunc.function = pytest.mark.xfail(metafunc.function)
def pytest_terminal_summary(terminalreporter):
if not hasattr(terminalreporter.config, '_wish_index_items'):
return
hit_state = 'passed' if terminalreporter.config.getoption('wish_fail') else 'xpassed'
hits = terminalreporter.getreports(hit_state)
terminalreporter.write_sep('=', '%d hit' % len(hits), bold=True)
terminalreporter.write_line('')
for report in hits:
terminalreporter.write(report.nodeid)
terminalreporter.write_line(' HIT', bold=True, green=True)
terminalreporter.write_line('')
|
Python
| 0
|
@@ -4411,43 +4411,8 @@
')%0A%0A
- config._warn('%25r' %25 locals())%0A%0A
|
0a765e620709dff244f32f0684e7fd5b6440215a
|
handle errors on resolve
|
lbrynet/extras/wallet/ledger.py
|
lbrynet/extras/wallet/ledger.py
|
import asyncio
import logging
from binascii import unhexlify
from torba.client.baseledger import BaseLedger
from lbrynet.schema.error import URIParseError
from lbrynet.schema.uri import parse_lbry_uri
from lbrynet.extras.wallet.dewies import dewies_to_lbc
from lbrynet.extras.wallet.resolve import Resolver
from lbrynet.extras.wallet.account import Account
from lbrynet.extras.wallet.network import Network
from lbrynet.extras.wallet.database import WalletDatabase
from lbrynet.extras.wallet.transaction import Transaction
from lbrynet.extras.wallet.header import Headers, UnvalidatedHeaders
log = logging.getLogger(__name__)
class MainNetLedger(BaseLedger):
name = 'LBRY Credits'
symbol = 'LBC'
network_name = 'mainnet'
headers: Headers
account_class = Account
database_class = WalletDatabase
headers_class = Headers
network_class = Network
transaction_class = Transaction
secret_prefix = bytes((0x1c,))
pubkey_address_prefix = bytes((0x55,))
script_address_prefix = bytes((0x7a,))
extended_public_key_prefix = unhexlify('0488b21e')
extended_private_key_prefix = unhexlify('0488ade4')
max_target = 0x0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
genesis_hash = '9c89283ba0f3227f6c03b70216b9f665f0118d5e0fa729cedf4fb34d6a34f463'
genesis_bits = 0x1f00ffff
target_timespan = 150
default_fee_per_byte = 50
default_fee_per_name_char = 200000
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fee_per_name_char = self.config.get('fee_per_name_char', self.default_fee_per_name_char)
@property
def resolver(self):
return Resolver(self.headers.claim_trie_root, self.headers.height, self.transaction_class,
hash160_to_address=self.hash160_to_address, network=self.network)
async def resolve(self, page, page_size, *uris):
for uri in uris:
try:
parse_lbry_uri(uri)
except URIParseError as err:
return {'error': err.args[0]}
resolutions = await self.network.get_values_for_uris(self.headers.hash().decode(), *uris)
return await self.resolver._handle_resolutions(resolutions, uris, page, page_size)
async def get_claim_by_claim_id(self, claim_id):
result = (await self.network.get_claims_by_ids(claim_id)).pop(claim_id, {})
return await self.resolver.get_certificate_and_validate_result(result)
async def get_claim_by_outpoint(self, txid, nout):
claims = (await self.network.get_claims_in_tx(txid)) or []
for claim in claims:
if claim['nout'] == nout:
return await self.resolver.get_certificate_and_validate_result(claim)
return 'claim not found'
async def start(self):
await super().start()
await asyncio.gather(*(a.maybe_migrate_certificates() for a in self.accounts))
await asyncio.gather(*(a.save_max_gap() for a in self.accounts))
await self._report_state()
async def _report_state(self):
for account in self.accounts:
total_receiving = len((await account.receiving.get_addresses()))
total_change = len((await account.change.get_addresses()))
channel_count = await account.get_channel_count()
claim_count = await account.get_claim_count()
balance = dewies_to_lbc(await account.get_balance())
log.info("Loaded account %s with %s LBC, %d receiving addresses (gap: %d), "
"%d change addresses (gap: %d), %d channels, %d certificates and %d claims. ",
account.id, balance, total_receiving, account.receiving.gap, total_change, account.change.gap,
channel_count, len(account.certificates), claim_count)
class TestNetLedger(MainNetLedger):
network_name = 'testnet'
pubkey_address_prefix = bytes((111,))
script_address_prefix = bytes((196,))
extended_public_key_prefix = unhexlify('043587cf')
extended_private_key_prefix = unhexlify('04358394')
class RegTestLedger(MainNetLedger):
network_name = 'regtest'
headers_class = UnvalidatedHeaders
pubkey_address_prefix = bytes((111,))
script_address_prefix = bytes((196,))
extended_public_key_prefix = unhexlify('043587cf')
extended_private_key_prefix = unhexlify('04358394')
max_target = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
genesis_hash = '6e3fcf1299d4ec5d79c3a4c91d624a4acf9e2e173d95a1a0504f677669687556'
genesis_bits = 0x207fffff
target_timespan = 1
|
Python
| 0.000001
|
@@ -1998,87 +1998,8 @@
- except URIParseError as err:%0A return %7B'error': err.args%5B0%5D%7D%0A
@@ -2092,16 +2092,179 @@
*uris)%0A
+ except URIParseError as err:%0A return %7B'error': err.args%5B0%5D%7D%0A except Exception as e:%0A return %7B'error': str(e)%7D%0A
|
8680a745956ad948d83fe845931f75c814a23c70
|
Change the SET_COM_PIN_CFG setting.
|
drivers/display/ssd1306.py
|
drivers/display/ssd1306.py
|
# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
from micropython import const
import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)
# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
class SSD1306(framebuf.FrameBuffer):
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
self.init_display()
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR,
0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO,
self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET,
0x00,
SET_COM_PIN_CFG,
0x02 if self.height == 32 else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV,
0x80,
SET_PRECHARGE,
0x22 if self.external_vcc else 0xF1,
SET_VCOM_DESEL,
0x30, # 0.83*Vcc
# display
SET_CONTRAST,
0xFF, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP,
0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01,
): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP | 0x00)
def poweron(self):
self.write_cmd(SET_DISP | 0x01)
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def show(self):
x0 = 0
x1 = self.width - 1
if self.width == 64:
# displays with width of 64 pixels are shifted by 32
x0 += 32
x1 += 32
self.write_cmd(SET_COL_ADDR)
self.write_cmd(x0)
self.write_cmd(x1)
self.write_cmd(SET_PAGE_ADDR)
self.write_cmd(0)
self.write_cmd(self.pages - 1)
self.write_data(self.buffer)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
self.write_list = [b"\x40", None] # Co=0, D/C#=1
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
def write_data(self, buf):
self.write_list[1] = buf
self.i2c.writevto(self.addr, self.write_list)
class SSD1306_SPI(SSD1306):
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
self.rate = 10 * 1024 * 1024
dc.init(dc.OUT, value=0)
res.init(res.OUT, value=0)
cs.init(cs.OUT, value=1)
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
import time
self.res(1)
time.sleep_ms(1)
self.res(0)
time.sleep_ms(10)
self.res(1)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(0)
self.cs(0)
self.spi.write(bytearray([cmd]))
self.cs(1)
def write_data(self, buf):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs(1)
self.dc(1)
self.cs(0)
self.spi.write(buf)
self.cs(1)
|
Python
| 0
|
@@ -1682,20 +1682,31 @@
elf.
+width %3E 2 * self.
height
- == 32
els
|
4bbaa4170c77d8ab9c28df33c20cf3b86b003056
|
allow replaying (shared lists bug), new voice line
|
alexBot/cogs/nOfThesePeopleAreLying.py
|
alexBot/cogs/nOfThesePeopleAreLying.py
|
import random
from typing import Dict, List
import discord
from discord import ButtonStyle, Interaction, Member, app_commands, ui
from ..tools import Cog
RANDOM_ARTICLES = ["The Statue Of Liberty", "The Eifle Tower", "Bass Pro Shop Pyramid", "The Taj Mahal", "Fortnite"]
class ArticalModal(ui.Modal, title="My Article Is..."):
article = ui.TextInput(label="Article Name", placeholder=random.choice(RANDOM_ARTICLES))
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.defer()
class FinishView(ui.View):
def __init__(self, articleOwner: Member, tomId):
super().__init__(timeout=840)
self.tomId = tomId
self.articleOwner: Member = articleOwner
@ui.button(label="the answer was...")
async def answer(self, interaction: discord.Interaction, button: ui.Button):
await interaction.response.send_message(
f"the article was chosen by {self.articleOwner.display_name}", ephemeral=interaction.user.id != self.tomId
)
if interaction.user.id == self.tomId:
self.stop()
class nOfThesePeopleAreLying(Cog):
class ImPlaying(ui.View):
players: List[Interaction] = []
orig = None
@ui.button(label="I'm playing!")
async def playerConfirm(self, interaction: Interaction, button: ui.Button):
if interaction.user.id in [p.user.id for p in self.players]:
return await interaction.response.send_message("you've already joined!", ephemeral=True)
self.players.append(interaction)
await interaction.response.send_message("i got you!", ephemeral=True)
if len(self.players) == 3:
self.startGame.disabled = False
await self.orig(
content=f"are you playing? hit 'I'm Playing'! I've Got {len(self.players)} players so far!", view=self
)
@ui.button(label="Let's Play!", style=ButtonStyle.green, disabled=True)
async def startGame(self, interaction: Interaction, button: ui.Button):
await interaction.response.defer(ephemeral=True)
self.stop()
class Articles(ui.View):
def __init__(self, players: List[Interaction], tomId):
super().__init__(timeout=None)
self.articles: Dict[int, str] = {}
self.players = players
self.player_ids = [p.user.id for p in self.players]
self.tomId = tomId
self.add_item(
ui.Button(label="Random Wikipedia Article", url="https://en.wikipedia.org/wiki/Special:Random")
)
@ui.button(label="My Articles is...", style=ButtonStyle.green)
async def articlesSet(self, interaction: discord.Interaction, button: ui.Button):
m = ArticalModal()
if interaction.user.id not in self.player_ids:
return await interaction.response.send_message("You're not playing!", ephemeral=True)
if interaction.user.id == self.tomId:
return await interaction.response.send_message(
"You are playing as Tom, and don't pick an article.", ephemeral=True
)
if interaction.user.id in self.articles:
return await interaction.response.send_message("You arleady responded!", ephemeral=True)
await interaction.response.send_modal(m)
if not await m.wait(): # this is dum
self.articles[interaction.user.id] = m.article.value
if len(self.players) == len(self.articles):
self.stop()
@app_commands.guilds(discord.Object(791528974442299412))
@app_commands.command(name="n-of-these-people-are-lying")
async def nLyers(self, interaction: Interaction):
v = self.ImPlaying(timeout=None)
v.orig = interaction.edit_original_message
await interaction.response.send_message("are you playing? hit 'I'm Playing'! ", view=v)
await v.wait()
players = v.players
tom = players.pop(random.randrange(len(players)))
articles = self.Articles(players, tom.user.id)
await interaction.followup.send(
f"alright! i need {', '.join([player.user.display_name for player in players])} to each go to wikipedia and grab a random article, then let me know the name of it. {tom.user.display_name} will be guessing who's got the article once all of you submit it.\n\nRemember, you don't have to pick the first article you get on the Random button.",
view=articles,
)
await articles.wait()
uid, article = random.choice(list(articles.articles.items()))
finish = FinishView(interaction.guild.get_member(uid), tom.user.id)
await interaction.followup.send(f"Alright, out of everyone's Articles, we got... {article}!", view=finish)
async def setup(bot):
await bot.add_cog(nOfThesePeopleAreLying(bot))
|
Python
| 0
|
@@ -1166,24 +1166,123 @@
w):%0A
+def __init__(self, *, timeout=180):%0A super().__init__(timeout=timeout)%0A self.
players: Lis
@@ -1309,16 +1309,25 @@
+ self.
orig = N
@@ -2440,10 +2440,14 @@
%5D =
-%7B%7D
+dict()
%0A
@@ -4329,16 +4329,21 @@
'.join(%5B
+f'**%7B
player.u
@@ -4358,16 +4358,20 @@
lay_name
+%7D**'
for pla
@@ -4855,32 +4855,627 @@
), tom.user.id)%0A
+ await tom.followup.send(f%22We're %7Binteraction.guild.name%7D and this is %7Blen(v.players) - 1%7D of these people are lying because %7Blen(v.players) - 1%7D of them will be. Currently the rest of the voice call is finding an article; after they have found an article and submitted it's name to Alexbot it Will randomly select one of the names. After the title has been selected one of the people will be telling the truth and the rest will be lying. It is your job to correctly guess who is telling the truth. If you guess who wrong, the person who deceive you will get the point.%22, ephemeral=True)%0A
await in
|
0b11bf48989673245adbc89aa6f65c85debafd9f
|
Make sure billing/shipping aren't populated if they aren't there
|
armstrong/apps/donations/backends.py
|
armstrong/apps/donations/backends.py
|
from armstrong.utils.backends import GenericBackend
from billing import get_gateway
from . import forms
class AuthorizeNetBackend(object):
def get_form_class(self):
return forms.CreditCardDonationForm
def purchase(self, donation, form):
authorize = get_gateway("authorize_net")
authorize.purchase(donation.amount,
form.get_credit_card(donation.donor),
options=self.get_options(donation))
def get_options(self, donation):
donor = donation.donor
return {
"billing_address": {
"name": donor.name,
"address1": donor.address.address,
"city": donor.address.city,
"state": donor.address.state,
# TODO: Support other countries
"country": "US",
"zip": donor.address.zipcode,
},
"shipping_address": {
"name": donor.name,
"address1": donor.mailing_address.address,
"city": donor.mailing_address.city,
"state": donor.mailing_address.state,
# TODO: Support other countries
"country": "US",
"zip": donor.mailing_address.zipcode,
}
}
raw_backend = GenericBackend("ARMSTRONG_DONATIONS_BACKEND", defaults=[
"armstrong.apps.donations.backends.AuthorizeNetBackend",
])
get_backend = raw_backend.get_backend
|
Python
| 0
|
@@ -531,15 +531,13 @@
r
-eturn
+ =
%7B
+%7D
%0A
@@ -541,20 +541,48 @@
-
+if donor.address:%0A r%5B
%22billing
@@ -582,33 +582,35 @@
billing_address%22
-:
+%5D =
%7B%0A
@@ -913,17 +913,50 @@
%7D
-,
+%0A if donor.mailing_address:
%0A
@@ -960,16 +960,18 @@
+r%5B
%22shippin
@@ -980,17 +980,19 @@
address%22
-:
+%5D =
%7B%0A
@@ -1344,17 +1344,25 @@
-%7D
+return r%0A
%0A%0Araw_ba
|
c69d33b1d7ae22834cfdbeb4b3f07c7ed10fb0fd
|
Handle exception message with single quotes
|
python/toree_client.py
|
python/toree_client.py
|
#
# (C) Copyright IBM Corp. 2017
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import time
from wrappers import *
from pprint import pprint
from util import debug_print, debug_pprint
from jupyter_client import BlockingKernelClient
try:
from queue import Empty # Python 3
except ImportError:
from Queue import Empty # Python 2
TIMEOUT = 30
class ToreeClient:
def __init__(self, connectionFileLocation):
self.client = BlockingKernelClient(connection_file=connectionFileLocation)
self.client.load_connection_file(connection_file=connectionFileLocation)
def is_alive(self):
return self.client.is_alive()
def is_ready(self):
try:
result = self.eval('1')
if result == '1':
return True
else:
return False
except:
return False
def wait_for_ready(self, timeout=TIMEOUT):
# Wait for initialization, by receiving an 'idle' message
# Flush Shell channel
abs_timeout = time.time() + timeout
while True:
try:
msg = self.client.shell_channel.get_msg(block=True, timeout=0.2)
except Empty:
break
# Check if current time is ready check time plus timeout
if time.time() > abs_timeout:
raise RuntimeError("Kernel didn't respond in %d seconds" % timeout)
# Flush IOPub channel
while True:
try:
msg = self.client.iopub_channel.get_msg(block=True, timeout=0.2)
except Empty:
break
# Check if current time is ready check time plus timeout
if time.time() > abs_timeout:
raise RuntimeError("Kernel didn't respond in %d seconds" % timeout)
def eval(self, code, timeout=TIMEOUT):
if self.client.is_alive() == False:
raise Exception('Problem connecting to remote kernel: Kernel is NOT alive')
debug_print('-----------------------------------------')
debug_print('Executing: ')
debug_pprint(code)
msg_id = self.client.execute(code=code, allow_stdin=False)
debug_print('Message id for code execution:' + msg_id)
# now the kernel should be 'busy' with [parent_header][msg_id] being the current message
busy_msg = self.client.iopub_channel.get_msg(timeout=1)
debug_print('checking current kernel status')
debug_print(busy_msg['parent_header']['msg_id'])
debug_print(busy_msg['content']['execution_state'])
debug_pprint(busy_msg)
if busy_msg['content']['execution_state'] == 'busy':
debug_print('busy_message')
else:
debug_print('error: not busy')
reply = self.client.get_shell_msg(timeout=3)
print('message reply')
pprint(reply)
type = ''
results = []
while True:
msg = self.client.get_iopub_msg()
debug_print('message')
debug_pprint(msg)
# validate that the responses are still related to current request
if msg['parent_header']['msg_id'] != msg_id:
debug_print('Ignoring messages related to ' + msg['parent_header']['msg_id'] + ' request')
#raise Exception('Invalid message id received ' + msg['parent_header']['msg_id'] + ' expected ' + msg_id)
# When idle, responses have all been processed/returned
elif msg['msg_type'] == 'status':
debug_print('current message status: ' + msg['msg_type'])
if msg['content']['execution_state'] == 'idle':
break
# validate execute_inputs are from current code
elif msg['msg_type'] == 'execute_input':
debug_print('current message status: ' + msg['msg_type'])
debug_print('current message content code: ' + msg['content']['code'])
if msg['content']['code'] == code:
continue
elif msg['msg_type'] == 'stream':
type = 'stream'
results.append(msg['content']['text'])
continue
elif msg['msg_type'] == 'execute_result':
if 'text/plain' in msg['content']['data']:
type = 'text'
results.append(msg['content']['data']['text/plain'])
elif 'text/html' in msg['content']['data']:
type = 'html'
results.append(msg['content']['data']['text/html'])
continue
if reply['content']['status'] == 'ok':
debug_print('Returning sucessful invocation')
if type == 'html':
html = ''.join(results)
htmlWrapper = HtmlOutput(html)
return htmlWrapper
else:
return ''.join(results)
else:
debug_print('Returning failed invocation')
raise Exception("Error: %s - %s" %(reply['content']['ename'], reply['content']['evalue']))
"""
client = ToreeClient('/Users/lresende/opensource/jupyter/toree-gateway/profiles/profile.json')
print('is alive: %s' % client.is_alive())
print('is ready: %s' % client.is_ready())
command = '''print(1+1)\nprint(2+2)\n3'''
pprint(client.eval(command))
command = '''print(1/0)'''
pprint(client.eval(command))
#result = client.eval(command)
#print('Result: ' + pprint(result))
"""
|
Python
| 0.000001
|
@@ -5532,17 +5532,17 @@
ception(
-%22
+'
Error: %25
@@ -5547,17 +5547,17 @@
%25s - %25s
-%22
+'
%25(reply
|
d167d79e5de0479bd3ddeeb0e7b03c5de6bb9ad5
|
fix key error
|
iceprod/server/scheduled_tasks/dataset_monitor.py
|
iceprod/server/scheduled_tasks/dataset_monitor.py
|
"""
Monitor the datasets.
Send monitoring data to graphite.
Initial delay: rand(1 minute)
Periodic delay: 5 minutes
"""
import logging
import random
import time
from tornado.ioloop import IOLoop
from iceprod.server import GlobalID
logger = logging.getLogger('dataset_monitor')
def dataset_monitor(module):
"""
Initial entrypoint.
Args:
module (:py:class:`iceprod.server.modules.schedule`): schedule module
"""
# initial delay
IOLoop.current().call_later(random.randint(5,60), run,
module.rest_client, module.statsd)
async def run(rest_client, statsd, debug=False):
"""
Actual runtime / loop.
Args:
rest_client (:py:class:`iceprod.core.rest_client.Client`): rest client
statsd (:py:class:`statsd.StatsClient`): statsd (graphite) client
debug (bool): debug flag to propagate exceptions
"""
start_time = time.time()
try:
datasets = await rest_client.request('GET', '/dataset_summaries/status')
for status in datasets:
for dataset_id in datasets[status]:
dataset = await rest_client.request('GET', '/datasets/{}'.format(dataset_id))
dataset_num = dataset['dataset']
dataset_status = dataset['status']
jobs = await rest_client.request('GET', '/datasets/{}/job_counts/status'.format(dataset_id))
for status in jobs:
if dataset_status in ('suspended','errors') and status == 'processing':
jobs['suspended'] == jobs[status]
jobs[status] = 0
for status in ('processing','failed','suspended','errors','complete'):
if status not in jobs:
jobs[status] = 0
statsd.gauge('datasets.{}.jobs.{}'.format(dataset_num,status), jobs[status])
tasks = await rest_client.request('GET', '/datasets/{}/task_counts/name_status'.format(dataset_id))
for name in tasks:
for status in tasks[name]:
if dataset_status in ('suspended','errors') and status in ('waiting','queued','processing'):
tasks[name]['suspended'] += tasks[name][status]
tasks[name][status] = 0
for status in ('idle','waiting','queued','processing','reset','failed','suspended','complete'):
if status not in tasks[name]:
tasks[name][status] = 0
statsd.gauge('datasets.{}.tasks.{}.{}'.format(dataset_num,name,status), tasks[name][status])
except Exception:
logger.error('error monitoring datasets', exc_info=True)
if debug:
raise
# run again after 60 minute delay
stop_time = time.time()
delay = max(60*5 - (stop_time-start_time), 60)
IOLoop.current().call_later(delay, run, rest_client, statsd)
|
Python
| 0.000006
|
@@ -2203,24 +2203,204 @@
ocessing'):%0A
+ if 'suspended' not in tasks%5Bname%5D:%0A tasks%5Bname%5D%5B'suspended'%5D = tasks%5Bname%5D%5Bstatus%5D%0A else:%0A
|
c82a9583d3001e39a2ff3eb929c37ed775c66856
|
add docstring stub
|
analysis/generate_model_predictions.py
|
analysis/generate_model_predictions.py
|
import pandas as pd
import numpy as np
import os
import analysis_helpers as h
split_types = ['balancedavg1','balancedavg2','balancedavg3','balancedavg4','balancedavg5']
model_space = ['human_combined_cost','multimodal_fc6_combined_cost','multimodal_conv42_combined_cost',
'multimodal_fc6_S0_cost','multimodal_fc6_combined_nocost']
if __name__ == "__main__":
import argparse
parser.add_argument('--model', type=str,
help='which model? human_combined_cost | \
multimodal_fc6_combined_cost | \
multimodal_conv42_combined_cost |\
multimodal_fc6_S0_cost | \
multimodal_fc6_combined_nocost | ', \
default='human_combined_cost')
parser.add_argument('--split_type', type=str,
help='which split? balancedavg1 | \
balancedavg2 | \
balancedavg3 | \
balancedavg4 | \
balancedavg5 |',
default='balancedavg1')
parser.add_argument('--predpath', type=str,
help='full path to evaluate output',
default='/data5/jefan/sketchpad_basic_model_output/evaluateOutput')
parser.add_argument('--costpath', type=str,
help='base path to cost dictionary for this split',
default='../models/refModule/json')
parser.add_argument('--parampath', type=str,
help='base path to param posterior for for this split and model',
default='../models/bdaOutput')
args = parser.parse_args()
## get name of model and split type to get predictions for
model = args.model
split_type = args.split_type
## get list of prediction files
path_to_evaluate = os.path.join(args.predpath,'{}_{}'.format(model,split_type))
pred_files = [os.path.join(path_to_evaluate,i) for i in os.listdir(path_to_evaluate)]
## load cost dictionary for this split
path_to_costs = os.path.join(args.costpath,'{}/costs-fixedPose96-cost_duration-average.json'.format(split_type))
J = h.load_json(path_to_costs)
## get file with params from this model
if model.split('_')[0]=='human':
bdaOutDir = '_'.join(model.split('_')[:1]) + '_{}'.format(split_type)
else:
bdaOutDir = '_'.join(model.split('_')[:2]) + '_{}'.format(split_type)
params_fname = model + '_' + split_type + 'ParamsFlattened.csv'
params_path = os.path.join(args.parampath,bdaOutDir,'flattened',params_fname)
params = pd.read_csv(params_path)
assert np.round(np.sum(np.exp(params.posteriorProb.values)),12)==1
## get list of all predictives (accepted MCMC samples) and
h.sort_filelist(pred_files) ## sort pred_files into human ordering
Obj = []
Cond = []
TargetRank = []
FoilRank = []
Logprob = []
SampleID = []
Trial = []
Adaptor = []
Cost = []
## loop through MCMC samples
for i,this_sample in enumerate(pred_files):
print 'Currently evaluating {} {}'.format(model,split_type)
print'{} | sample ID: {} '.format(i,int(this_sample.split('/')[-1].split('Predictives.csv')[0]))
## read in predictions from this sample
sample_preds = pd.read_csv(this_sample)
sample_ind = int(this_sample.split('/')[-1].split('Predictives.csv')[0]) ## index of MCMC sample
clear_output(wait=True)
## get params that generated these predictions
# simScaling = params.iloc[sample_ind]['simScaling']
# pragWeight = params.ilo gc[sample_ind]['pragWeight']
# costWeight = params.iloc[sample_ind]['costWeight']
# infWeight = params.iloc[sample_ind]['infWeight']
# posteriorProb = params.iloc[sample_ind]['posteriorProb']
# logLikelihood = params.iloc[sample_ind]['logLikelihood']
## get congruent/incongruent context log odds for each sketch
trials = np.unique(sample_preds['game'].values)
for this_trial in trials:
## subset the rows that correspond to this particular trial
trial_inds = sample_preds['game']==this_trial
these_rows = sample_preds[trial_inds]
assert np.round(sum(np.exp(these_rows['modelProb'].values)),6)==1
## sort the 64 sketch categories by model probability
sorted_rows = these_rows.sort_values(by=['modelProb'],ascending=False).reset_index()
## get target rank, logprob, prob
target = np.unique(sorted_rows['TrueSketch'].values)[0]
if target.split('_')[0]=='closer':
foil = 'further_{}'.format(target.split('_')[1])
elif target.split('_')[0]=='further':
foil = 'closer_{}'.format(target.split('_')[1])
target_rank = sorted_rows.index[sorted_rows['PossibleSketch']==target].tolist()[0]+1
foil_rank = sorted_rows.index[sorted_rows['PossibleSketch']==foil].tolist()[0]+1
target_logprob = sorted_rows.iloc[target_rank]['modelProb']
target_prob = np.exp(target_logprob)
obj = sorted_rows.iloc[target_rank]['Target']
condition = sorted_rows.iloc[target_rank]['condition']
## now get average cost of sketch produced for this trial, weighted by probability
## of each sketch category
sorted_rows['cost'] = sorted_rows['PossibleSketch'].map(J) ## add cost column to sorted_rows
_cost = sorted_rows.apply(h.weight_cost_by_modelProb,axis=1).sum() ## sum
Obj.append(obj)
Cond.append(condition)
TargetRank.append(target_rank)
FoilRank.append(foil_rank)
Logprob.append(target_logprob)
SampleID.append(sample_ind)
Trial.append(this_trial)
Adaptor.append(model)
Cost.append(_cost)
## make dataframe
print 'Now making dataframe'
X = pd.DataFrame([Obj,Cond,TargetRank,FoilRank,Logprob,SampleID,Trial,Adaptor,Cost])
X = X.transpose()
X.columns = ['object','condition','target_rank','foil_rank','logprob','sample_ind','trial','adaptor','cost']
if not os.path.exists('./csv'):
os.makedirs('./csv')
X.to_csv('./csv/{}_{}_predictions.csv'.format(model,split_type))
print 'Dataframe successfully saved out.'
|
Python
| 0.000001
|
@@ -72,16 +72,286 @@
s as h%0A%0A
+'''%0ASee the script get_all_model_predictions.py, which is a wrapper around %0Athis script, generate_model_predictions.py to generate csv files that %0Asummarize key statistics of interest (e.g., target rank, cost)%0Afrom model predictions, for each model and data split.%0A'''%0A%0A
split_ty
|
6ecc3fde7e0a7f767da161f627ad17f4cc249bb9
|
Add AppPath class.
|
ievv_opensource/utils/ievvbuildstatic/filepath.py
|
ievv_opensource/utils/ievvbuildstatic/filepath.py
|
import os
from django.apps import apps
class FilePathInterface(object):
"""
Base interface for file path objects.
We provide subclasses if this interface with different use cases:
- :class:`.SourcePath`: Use this to specify a source file or folder
in the sources directory of a :class:`ievv_opensource.utils.ievvbuildstatic.config.App`.
- :class:`.DestinationPath`: Use this to specify a destination file or folder
in the sources directory of a :class:`ievv_opensource.utils.ievvbuildstatic.config.App`.
- :class:`.AbsoluteFilePath`: Use this to specify a file or folder that is
not organized using the ievvbuildstatic directory layout.
"""
@property
def abspath(self):
"""
Property that returns the absolute path to the file (or directory).
Must be overridden in subclasses.
"""
raise NotImplementedError()
class AbsoluteFilePath(FilePathInterface):
"""
Absolute file path.
Works just like :func:`os.path.join`, and we just
assume that you provide a path that is absolute.
"""
def __init__(self, *path):
"""
Args:
*path: One or more strings that make up an absolute path
when joined with ``os.path.join(*path)``.
Returns:
"""
self._path = path
@property
def abspath(self):
return os.path.join(*self._path)
class AbstractDjangoAppPath(FilePathInterface):
"""
Abstract base class for file paths within a Django app.
"""
def get_approot_path(self, appname):
appconfig = apps.get_app_config(appname)
return appconfig.path
def get_approot_relative_path(self, appname, *path):
return os.path.join(self.get_approot_path(appname=appname), *path)
@property
def abspath(self):
raise NotImplementedError()
class SourcePath(AbstractDjangoAppPath):
"""
A path to a file or directory within the source directory of
a :class:`ievv_opensource.utils.ievvbuildstatic.config.App`.
Assumes that the sourcefolder of the App is ``"staticsources"`` (the default).
"""
def __init__(self, appname, *path):
"""
Args:
appname: The name of the Django app.
*path: The path relative to the source directory of the
:class:`ievv_opensource.utils.ievvbuildstatic.config.App`
identified by ``appname``. Same format as :func:`os.path.join`.
"""
self.appname = appname
self.path = path
@property
def abspath(self):
return self.get_approot_relative_path(self.appname, 'staticsources', self.appname, *self.path)
class DestinationPath(AbstractDjangoAppPath):
"""
A path to a file or directory within the destination directory of
a :class:`ievv_opensource.utils.ievvbuildstatic.config.App`.
Assumes that the destinationfolder of the App is ``"static"`` (the default).
"""
def __init__(self, appname, version, *path):
"""
Args:
appname: The name of the Django app.
version: The version of the app.
*path: The path relative to the destination directory of the
:class:`ievv_opensource.utils.ievvbuildstatic.config.App`
identified by ``appname``. Same format as :func:`os.path.join`.
"""
self.appname = appname
self.version = version
self.path = path
@property
def abspath(self):
return self.get_approot_relative_path(self.appname, 'static', self.appname, self.version, *self.path)
|
Python
| 0
|
@@ -3605,20 +3605,717 @@
ersion, *self.path)%0A
+%0A%0Aclass AppPath(AbstractDjangoAppPath):%0A %22%22%22%0A A path to a file or directory within the root directory of%0A a :class:%60ievv_opensource.utils.ievvbuildstatic.config.App%60.%0A %22%22%22%0A def __init__(self, appname, *path):%0A %22%22%22%0A Args:%0A appname: The name of the Django app.%0A *path: The path relative to the root directory of the%0A :class:%60ievv_opensource.utils.ievvbuildstatic.config.App%60%0A identified by %60%60appname%60%60. Same format as :func:%60os.path.join%60.%0A %22%22%22%0A self.appname = appname%0A self.path = path%0A%0A @property%0A def abspath(self):%0A return self.get_approot_relative_path(self.appname, *self.path)%0A
|
5efddf26176ac778556a3568bf97c2e70daac866
|
Replace many double quotes with single quotes
|
anchorhub/settings/default_settings.py
|
anchorhub/settings/default_settings.py
|
"""
Defaults for all settings used by AnchorHub
"""
WRAPPER = "{ }"
INPUT = "."
OUTPUT = "out-anchorhub"
ARGPARSER = {
"description": "anchorhub parses through Markdown files and precompiles "
"links to specially formatted anchors."
}
ARGPARSE_INPUT = {
"help": "Path of directory tree to be parsed",
}
ARGPARSE_OUTPUT = {
"help": "Desired output location (default is \"" + OUTPUT + "\")",
"default": OUTPUT
}
ARGPARSE_OVERWRITE = {
"help": "Overwrite input files; ignore output location"
}
ARGPARSE_EXTENSION = {
"help": "Indicate which file extensions to search and run anchorhub on.",
"default": [".md"]
}
ARGPARSE_WRAPPER = {
"help": "Specify custom wrapper format (default is \"" + WRAPPER + "\")",
"default": WRAPPER
}
|
Python
| 0.999999
|
@@ -60,13 +60,13 @@
R =
-%22%7B %7D%22
+'%7B %7D'
%0A%0AIN
@@ -75,11 +75,11 @@
T =
-%22.%22
+'.'
%0AOUT
@@ -84,17 +84,17 @@
UTPUT =
-%22
+'
out-anch
@@ -98,17 +98,17 @@
nchorhub
-%22
+'
%0A%0AARGPAR
@@ -119,17 +119,17 @@
= %7B%0A
-%22
+'
descript
@@ -131,17 +131,17 @@
cription
-%22
+'
: %22ancho
@@ -277,22 +277,22 @@
= %7B%0A
-%22
+'
help
-%22
+'
: %22Path
@@ -350,22 +350,22 @@
= %7B%0A
-%22
+'
help
-%22
+'
: %22Desir
@@ -421,25 +421,25 @@
)%22,%0A
-%22
+'
default
-%22
+'
: OUTPUT
@@ -468,22 +468,22 @@
= %7B%0A
-%22
+'
help
-%22
+'
: %22Overw
@@ -553,22 +553,22 @@
= %7B%0A
-%22
+'
help
-%22
+'
: %22Indic
@@ -631,25 +631,25 @@
.%22,%0A
-%22
+'
default
-%22
+'
: %5B%22.md%22
@@ -681,14 +681,14 @@
-%22
+'
help
-%22
+'
: %22S
@@ -759,17 +759,17 @@
-%22
+'
default
-%22
+'
: WR
|
0ac45656e3b76564d1e1752dd16ae91cfc918134
|
Set room maximum capacity
|
app/room.py
|
app/room.py
|
class Room(object):
"""Room class that creates rooms in amity
"""
def __init__(self, room_name, room_type, capacity, occupants):
self.room_name = room_name
self.room_type = room_type
self.capacity = capacity
self.occupants = []
class LivingSpace(Room):
"""Creates living spaces and inherits from Room"""
def __init__(self, room_name):
super(LivingSpace, self).__init__(
room_name, room_type="Living Space", capacity=4, occupants=[])
class Office(Room):
"""Creates offices and inherits from room"""
def __init__(self, room_name):
super(Office, self).__init__(
room_name, room_type="Office", capacity=4, occupants=[])
|
Python
| 0.000001
|
@@ -692,33 +692,33 @@
fice%22, capacity=
-4
+6
, occupants=%5B%5D)%0A
@@ -701,25 +701,24 @@
pacity=6, occupants=%5B%5D)%0A
-%0A
|
89bbea9d4c61e211740ae649a0f3f15bcb89a1a5
|
add device_type
|
lava-kernel-ci-job-creator.py
|
lava-kernel-ci-job-creator.py
|
#!/usr/bin/python
import urllib2
import urlparse
import re
import sys
import os
import shutil
base_url = None
kernel = None
dtb_list = []
dtb_map = {'exynos5250-arndale.dtb': 'arndale',
'am335x-boneblack.dtb': 'beaglebone-black',
'omap3-beagle-xm.dtb': 'beagle-xm',
'omap4-panda-es.dtb': 'panda',
'imx6dl-wandboard.dtb': 'imx6q-wandboard',
'imx6q-wandboard.dtb': 'imx6q-wandboard'}
parse_re = re.compile('href="([^"]*)".*(..-...-.... ..:..).*?(\d+[^\s<]*|-)')
def setup_job_dir(directory):
print 'Setting up JSON output directory at: jobs/'
if not os.path.exists(directory):
os.makedirs(directory)
else:
shutil.rmtree(directory)
os.makedirs(directory)
print 'Done setting up JSON output directory'
def create_jobs(base_url, kernel, dtb_list):
print 'Creating JSON Job Files...'
cwd = os.getcwd()
url = urlparse.urlparse(kernel)
build_info = url.path.split('/')
image_url = base_url
image_type = build_info[1]
tree = build_info[2]
kernel_version = build_info[3]
defconfig = build_info[4]
for dtb in dtb_list:
job_name = tree + '-' + kernel_version + '-' + defconfig + '-' + dtb.split('/')[-1]
job_json = cwd + '/jobs/' + job_name + '.json'
template_file = cwd + '/templates/kernel-ci-template.json'
with open(job_json, 'wt') as fout:
with open(template_file, "rt") as fin:
for line in fin:
tmp = line.replace('{dtb_url}', dtb)
tmp = tmp.replace('{kernel_url}', kernel)
#tmp = tmp.replace('{lava_server}', lava_server)
#tmp = tmp.replace('{bundle_stream}', bundle_stream)
#tmp = tmp.replace('{device_type}', device_type)
tmp = tmp.replace('{job_name}', job_name)
tmp = tmp.replace('{image_type}', image_type)
tmp = tmp.replace('{image_url}', image_url)
tmp = tmp.replace('{tree}', tree)
tmp = tmp.replace('{kernel_version}', kernel_version)
tmp = tmp.replace('{defconfig}', defconfig)
fout.write(tmp)
print 'JSON Job created: jobs/%s' % job_name
def walk_url(url):
global base_url
global kernel
global dtb_list
try:
html = urllib2.urlopen(url).read()
except IOError, e:
print 'error fetching %s: %s' % (url, e)
exit(1)
if not url.endswith('/'):
url += '/'
files = parse_re.findall(html)
dirs = []
for name, date, size in files:
if name.endswith('/'):
dirs += [name]
if name.endswith('zImage'):
kernel = url + name
base_url = url
if name.endswith('.dtb') and name in dtb_map:
dtb_list.append(url + name)
for dir in dirs:
if kernel is not None and base_url is not None and dtb_list:
print 'Found boot artifacts at: %s' % base_url
create_jobs(base_url, kernel, dtb_list)
base_url = None
kernel = None
dtb_list = []
walk_url(url + dir)
def main(url):
setup_job_dir(os.getcwd() + '/jobs')
print 'Scanning %s for boot information...' % url
walk_url(url)
print 'Done scanning for boot information'
print 'Done creating JSON jobs'
exit(0)
if __name__ == '__main__':
main(sys.argv[1])
|
Python
| 0.000008
|
@@ -1134,32 +1134,110 @@
tb in dtb_list:%0A
+ dtb_name = dtb.split('/')%5B-1%5D%0A device_type = dtb_map%5Bdtb_name%5D%0A
job_name
@@ -1292,39 +1292,29 @@
+ '-' + dtb
-.split('/')%5B-1%5D
+_name
%0A job
@@ -1824,33 +1824,32 @@
-#
tmp = tmp.replac
|
e3a84c3ccadb98ecb5dae563475de5108d46cf9d
|
Format external_plugin_dependencies.bzl with buildifier
|
external_plugin_deps.bzl
|
external_plugin_deps.bzl
|
load("//tools/bzl:maven_jar.bzl", "maven_jar")
def external_plugin_deps():
maven_jar(
name = "mockito",
artifact = "org.mockito:mockito-core:2.15.0",
sha1 = "b84bfbbc29cd22c9529409627af6ea2897f4fa85",
deps = [
"@byte_buddy//jar",
"@byte_buddy_agent//jar",
"@objenesis//jar",
],
)
BYTE_BUDDY_VER = "1.7.9"
maven_jar(
name = "byte_buddy",
artifact = "net.bytebuddy:byte-buddy:" + BYTE_BUDDY_VER,
sha1 = "51218a01a882c04d0aba8c028179cce488bbcb58",
)
maven_jar(
name = "byte_buddy_agent",
artifact = "net.bytebuddy:byte-buddy-agent:" + BYTE_BUDDY_VER,
sha1 = "a6c65f9da7f467ee1f02ff2841ffd3155aee2fc9",
)
maven_jar(
name = "objenesis",
artifact = "org.objenesis:objenesis:2.6",
sha1 = "639033469776fd37c08358c6b92a4761feb2af4b",
)
|
Python
| 0.000001
|
@@ -69,16 +69,18 @@
deps():%0A
+
maven_
@@ -76,32 +76,36 @@
%0A maven_jar(%0A
+
name = %22mock
@@ -110,16 +110,20 @@
ckito%22,%0A
+
arti
@@ -164,24 +164,28 @@
.15.0%22,%0A
+
+
sha1 = %22b84b
@@ -223,16 +223,20 @@
4fa85%22,%0A
+
deps
@@ -240,16 +240,22 @@
eps = %5B%0A
+
%22@
@@ -264,32 +264,38 @@
te_buddy//jar%22,%0A
+
%22@byte_bud
@@ -306,24 +306,30 @@
gent//jar%22,%0A
+
%22@obje
@@ -345,20 +345,28 @@
r%22,%0A
+
%5D,%0A
+
)%0A%0A
+
BY
@@ -389,16 +389,18 @@
1.7.9%22%0A%0A
+
maven_
@@ -400,32 +400,36 @@
maven_jar(%0A
+
+
name = %22byte_bud
@@ -433,24 +433,28 @@
buddy%22,%0A
+
+
artifact = %22
@@ -490,32 +490,36 @@
BYTE_BUDDY_VER,%0A
+
sha1 = %225121
@@ -555,27 +555,31 @@
8bbcb58%22,%0A
+
+
)%0A%0A
+
maven_jar(
@@ -571,32 +571,36 @@
%0A maven_jar(%0A
+
name = %22byte
@@ -614,16 +614,20 @@
agent%22,%0A
+
arti
@@ -681,24 +681,28 @@
_BUDDY_VER,%0A
+
sha1 = %22
@@ -744,21 +744,25 @@
e2fc9%22,%0A
+
)%0A%0A
+
maven_
@@ -762,24 +762,28 @@
maven_jar(%0A
+
name = %22
@@ -794,16 +794,20 @@
nesis%22,%0A
+
arti
@@ -844,16 +844,20 @@
s:2.6%22,%0A
+
sha1
@@ -903,13 +903,14 @@
2af4b%22,%0A
+
)%0A
-%0A
|
0a902a5afd43fe817320bd1e400828abcd1faa83
|
make su promt AIX compatible
|
lib/ansible/utils/su_prompts.py
|
lib/ansible/utils/su_prompts.py
|
# -*- coding: utf-8 -*-
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
import re
SU_PROMPT_LOCALIZATIONS = [
'Password',
'암호',
'パスワード',
'Adgangskode',
'Contraseña',
'Contrasenya',
'Hasło',
'Heslo',
'Jelszó',
'Lösenord',
'Mật khẩu',
'Mot de passe',
'Parola',
'Parool',
'Pasahitza',
'Passord',
'Passwort',
'Salasana',
'Sandi',
'Senha',
'Wachtwoord',
'ססמה',
'Лозинка',
'Парола',
'Пароль',
'गुप्तशब्द',
'शब्दकूट',
'సంకేతపదము',
'හස්පදය',
'密码',
'密碼',
]
SU_PROMPT_LOCALIZATIONS_RE = re.compile("|".join([x + ' ?: ?' for x in SU_PROMPT_LOCALIZATIONS]), flags=re.IGNORECASE)
def check_su_prompt(data):
return bool(SU_PROMPT_LOCALIZATIONS_RE.match(data))
|
Python
| 0
|
@@ -1285,16 +1285,31 @@
%22.join(%5B
+'(%5Cw+%5C's )?' +
x + ' ?:
|
b19fa5114fa3e363a634defa9d4299ec7562c607
|
Make p_debug more terse: print test in same line as `DEBUG` prefix.
|
libexec/windows_shares_discovery_runner.py
|
libexec/windows_shares_discovery_runner.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
#
# This file is part of Shinken.
#
# Shinken 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.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
import optparse
import sys
import os
import subprocess
VERSION = '1.0'
parser = optparse.OptionParser(
"%prog [options] -H HOSTADRESS -u DOMAIN\\USER -p PASSWORD",
version="%prog " + VERSION)
parser.add_option('-H', "--hostname",
help="Hostname to scan")
parser.add_option('-u', '--user', default='guest',
help="Username to scan with. Default to '%default'")
parser.add_option('-p', '--password', default='',
help="Password of your user. Default to ''")
parser.add_option('-d', "--debug", action='store_true',
help="Debug mode")
opts, args = parser.parse_args()
if not opts.hostname:
parser.error("Requires one host to scan (option -H)")
hostname = opts.hostname
# The username may contain a domains like in `DOMAIN\user`. We must
# protect the the `\` with another one for the command-line call.
user = opts.user.replace('\\', '\\\\')
debug = opts.debug
password = opts.password
cred = '%s%%%s' % (user, password)
def p_debug(s):
if debug:
print "DEBUG"
print s
cmd = "smbclient --user=%s --grepable -L %s" % (cred, hostname)
p_debug("Launching command, %s" % cmd)
try:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
close_fds=True, shell=True)
except OSError, exp:
print "Error in launching command:", cmd, exp
sys.exit(2)
p_debug("Try to communicate with the subprocess")
(stdoutdata, stderrdata) = process.communicate()
if process.returncode != 0:
print "Error: the share scanner return an error: '%s'" % (stderrdata + stdoutdata)
sys.exit(2)
disks = []
printers = []
p_debug("Good return" + stdoutdata)
def get_elements(line):
if line.count('|') < 2:
p_debug("Not a good line" + line)
return None
elts = line.split('|', 2)
return elts
for line in stdoutdata.splitlines():
line = line.strip()
elts = get_elements(line)
# Avoid strange line
if not elts:
continue
typ = elts[0]
sharename = elts[1]
desc = elts[2]
if typ == 'Printer':
printers.append(sharename)
if typ == 'Disk' and not sharename.endswith('$'):
disks.append(sharename)
if len(disks) > 0:
print "%s::shares_detected=1"
print "%s::_shares=%s" % (hostname, ','.join(disks))
if len(printers) > 0:
print "%s::printers_detected=1"
print "%s::_printers=%s" % (hostname, ','.join(printers))
|
Python
| 0.000013
|
@@ -15,16 +15,18 @@
python%0A
+#%0A
# Copyri
@@ -1852,17 +1852,16 @@
sword)%0A%0A
-%0A
def p_de
@@ -1906,23 +1906,11 @@
EBUG
-%22%0A print
+:%22,
s%0A%0A
|
6e2219643d789038b79ba80bd6be632836e81ce5
|
Add app_label to UniversityIDSettings
|
lms/djangoapps/edraak_university/models.py
|
lms/djangoapps/edraak_university/models.py
|
"""
Models for the University ID apps.
"""
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.utils.translation import ugettext, ugettext_lazy as _
from courseware.courses import get_course_by_id
from openedx.core.djangoapps.course_groups.cohorts import (
DEFAULT_COHORT_NAME,
add_user_to_cohort,
get_cohort,
remove_user_from_cohort,
get_course_cohorts,
)
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
from student.models import UserProfile
DEFAULT_COHORT_NAMES = [
# edX chose to translate `DEFAULT_COHORT_NAME`, this is a disaster for Arabic platforms!
"Default Group",
ugettext("Default Group"),
]
class UniversityID(models.Model):
"""
Stores a the university ID and the section number for a students in university-run courses.
"""
user = models.ForeignKey(User)
course_key = CourseKeyField(max_length=255, db_index=True)
university_id = models.CharField(verbose_name=_('Student University ID'), max_length=100)
# This is set=True once an instructor edits a student's record
can_edit = models.BooleanField(default=True)
date_created = models.DateTimeField(default=timezone.now)
# Deprecated fields, kept for backward compatibility
_section_number = models.CharField(db_column='section_number', max_length=10, blank=True, default='')
_cohort = models.IntegerField(db_column='cohort_id', null=True)
# Will be used in `get_marked_university_ids()` method to mark
# duplicate entries.
is_conflicted = False
def get_cohort(self):
return get_cohort(self.user, self.course_key)
def set_cohort(self, cohort):
current_cohort = self.get_cohort()
if cohort.id != current_cohort.id:
add_user_to_cohort(cohort, self.user.email)
def remove_from_cohort(self):
cohort = self.get_cohort()
remove_user_from_cohort(cohort, username_or_email=self.user.email)
def get_full_name(self):
"""
Gets the student's full name, or none in case the user had no profile.
"""
try:
user_profile = UserProfile.objects.get(user=self.user)
return user_profile.name
except UserProfile.DoesNotExist:
return None
def get_email(self):
"""
Gets the student's email.
"""
return self.user.email
@classmethod
def get_cohorts_for_course(cls, course_key):
course = get_course_by_id(course_key)
cohorts_choices = [
cohort for cohort in get_course_cohorts(course=course)
if cohort.name not in DEFAULT_COHORT_NAMES
]
return cohorts_choices
def __unicode__(self):
return u'{user} - {course_key} - {university_id}'.format(
user=self.user,
course_key=self.course_key,
university_id=self.university_id,
)
@classmethod
def get_marked_university_ids(cls, course_key):
"""
Get all university IDs for a course and mark duplicate as `is_conflicted`.
"""
queryset = cls.objects.filter(course_key=course_key)
queryset = queryset.order_by('university_id')
def cleanup_id(university_id_pk):
"""
Trim an ID to make it easier to compare.
"""
return university_id_pk.strip().lower()
entries = list(queryset)
for i, entry in enumerate(entries):
if i > 0: # Avoid IndexError
prev_entry = entries[i - 1]
if cleanup_id(entry.university_id) == cleanup_id(prev_entry.university_id):
entry.is_conflicted = True
prev_entry.is_conflicted = True
return entries
class Meta:
unique_together = ('user', 'course_key',)
app_label = 'edraak_university'
class UniversityIDSettings(models.Model):
"""
This model stores university id settings for each course.
"""
course_key = CourseKeyField(primary_key=True, max_length=255, db_index=True)
registration_end_date = models.DateField(null=True, blank=True, verbose_name=_('Registration End Date'))
terms_and_conditions = models.TextField(null=True, blank=True, verbose_name=_('Terms and Conditions'))
def __unicode__(self):
return unicode(self.course_key)
|
Python
| 0.000001
|
@@ -4384,24 +4384,81 @@
nicode(self.course_key)%0A
+%0A class Meta:%0A app_label = 'edraak_university'%0A
|
ed09faba07647cbb67968e3f6c9d001dec8def98
|
Rename tests to follow good naming convention.
|
localized_recurrence/tests/fields_tests.py
|
localized_recurrence/tests/fields_tests.py
|
import unittest
from datetime import timedelta
from mock import MagicMock, patch
from .. import fields
class Test_DurationField_to_python(unittest.TestCase):
def setUp(self):
"""Create a mock of the DurationField class and pin to_python to it.
"""
self.df = fields.DurationField()
def test_timedelta(self):
"""A timedelta should just get returned.
"""
td_in = timedelta(days=1, hours=3)
td_out = self.df.to_python(td_in)
self.assertEqual(td_out, td_in)
def test_string(self):
"""A string should be properly converted.
"""
td_expected = timedelta(days=3, hours=5, minutes=10)
str_in = str(td_expected)
td_out = self.df.to_python(str_in)
self.assertEqual(td_out, td_expected)
def test_bad_string(self):
"""Malformed strings should raise an error.
"""
str_in = "3:5"
with self.assertRaises(ValueError):
self.df.to_python(str_in)
def test_int(self):
"""Int inputs should give timedelta outputs
"""
int_in = 176400
td_expected = timedelta(days=2, hours=1)
td_out = self.df.to_python(int_in)
self.assertEqual(td_out, td_expected)
def test_none(self):
"""Null input -> None output
"""
td_in = None
td_out = self.df.to_python(td_in)
self.assertEqual(td_in, td_out)
def test_invalid(self):
"""Unsupported objects raise ValueError
"""
td_in = self
with self.assertRaises(ValueError):
self.df.to_python(td_in)
class Test_DurationField_get_prep_value(unittest.TestCase):
def setUp(self):
"""Create a mock of the DurationField class and pin get_prep_value.
"""
self.df = fields.DurationField()
def test_returns_int(self):
"""Type should be `int`.
"""
td_in = timedelta(hours=14)
int_out = self.df.get_prep_value(td_in)
self.assertTrue(isinstance(int_out, int))
def test_returns_int2(self):
"""Type should be `int`.
"""
td_in = timedelta(hours=14, seconds=3.5)
int_out = self.df.get_prep_value(td_in)
self.assertTrue(isinstance(int_out, int))
def test_round_trip(self):
"""A trip through get_prep_value and to_python.
"""
td_in = timedelta(hours=14)
int_out = self.df.get_prep_value(td_in)
td_out = self.df.to_python(int_out)
self.assertEqual(td_out, td_in)
class Test_DurationField_value_to_string(unittest.TestCase):
def setUp(self):
"""Create a mock of the DurationField class and pin value_to_string to it.
We also mock out the _get_val_from_obj, to just return what is
passed in. Allows us to pass in a timedelta for testing intead
of the expected object.
"""
self.mock_DurationField = MagicMock()
self.mock_DurationField.value_to_string = fields.DurationField.__dict__['value_to_string']
self.mock_DurationField.to_python = fields.DurationField.__dict__['to_python']
self.mock_DurationField._get_val_from_obj.side_effect = lambda x: x
def test_simple_string(self):
"""
"""
in_td = timedelta(days=1, hours=1, minutes=1, seconds=1)
expected_str = "1 day, 1:01:01"
out_str = self.mock_DurationField.value_to_string(self.mock_DurationField, in_td)
self.assertEqual(out_str, expected_str)
def test_loop_to_python(self):
"""A roundtrip through value_to_string and to_python.
We expect the value to be unchanged after the trip.
"""
in_td = timedelta(days=1, hours=1, minutes=1, seconds=1)
out_str = self.mock_DurationField.value_to_string(self.mock_DurationField, in_td)
out_td = self.mock_DurationField.to_python(self.mock_DurationField, out_str)
self.assertEqual(out_td, in_td)
class Test_parse_timedelta_string(unittest.TestCase):
"""Test some round trips between timedelta, string, timedelta.
"""
def test_works(self):
"""Test a bunch of cases for the regular expressions.
We test so many things in this test because regular
expressions represent a lot of effective branching.
"""
td1_in = timedelta(days=1)
td2_in = timedelta(seconds=1)
td3_in = timedelta(hours=1, minutes=1, seconds=1)
td4_in = timedelta(days=1, seconds=10000.001)
td5_in = timedelta(hours=12)
td6_in = timedelta(hours=-12)
str1_out = str(td1_in)
str2_out = str(td2_in)
str3_out = str(td3_in)
str4_out = str(td4_in)
str5_out = str(td5_in)
str6_out = str(td6_in)
td1_out = fields.parse_timedelta_string(str1_out)
td2_out = fields.parse_timedelta_string(str2_out)
td3_out = fields.parse_timedelta_string(str3_out)
td4_out = fields.parse_timedelta_string(str4_out)
td5_out = fields.parse_timedelta_string(str5_out)
td6_out = fields.parse_timedelta_string(str6_out)
self.assertEqual(td1_in, td1_out)
self.assertEqual(td2_in, td2_out)
self.assertEqual(td3_in, td3_out)
self.assertEqual(td4_in, td4_out)
self.assertEqual(td5_in, td5_out)
self.assertEqual(td6_in, td6_out)
class Test_setup_south(unittest.TestCase):
def test_no_south(self):
"""This test is meant to hit the branch handleing the ImportError for
south.
Some users may not have south, so if it is not available, we
just pass.
"""
with patch.dict('sys.modules', {'south.modelsinspector': {}}):
reload(fields)
|
Python
| 0
|
@@ -98,37 +98,32 @@
fields%0A%0A%0Aclass
-Test_
DurationField_to
@@ -119,26 +119,28 @@
ionField
-_to_p
+ToP
ython
+Test
(unittes
@@ -1615,37 +1615,32 @@
(td_in)%0A%0A%0Aclass
-Test_
DurationField_ge
@@ -1640,23 +1640,24 @@
ield
-_get_prep_v
+GetPrepV
alue
+Test
(uni
@@ -2537,21 +2537,16 @@
%0A%0Aclass
-Test_
Duration
@@ -2554,24 +2554,25 @@
ield
-_v
+V
alue
-_to_s
+ToS
tring
+Test
(uni
@@ -3952,28 +3952,22 @@
ass
-Test_p
+P
arse
-_t
+T
imedelta
_str
@@ -3962,23 +3962,26 @@
imedelta
-_s
+S
tring
+Test
(unittes
@@ -5347,24 +5347,22 @@
ass
-Test_s
+S
etup
-_s
+S
outh
+Test
(uni
|
a402d356fbc5ec0a626af925694818d489c527b0
|
Remove unused import
|
localtv/management/commands/bulk_import.py
|
localtv/management/commands/bulk_import.py
|
# This file is part of Miro Community.
# Copyright (C) 2010 Participatory Culture Foundation
#
# Miro Community 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.
#
# Miro Community is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Miro Community. If not, see <http://www.gnu.org/licenses/>.
import os
import simplejson
import sys
from importlib import import_module
import feedparser
import eventlet
import eventlet.pools
from django.db import transaction
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from vidscraper.bulk_import import bulk_import_url_list, bulk_import
from localtv import models
import localtv.util
import localtv.tasks
DEFAULT_HTTPLIB_CACHE_PATH='/tmp/.cache-for-uid-%d' % os.getuid()
class Command(BaseCommand):
args = '[feed primary key]'
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError('bulk_import takes one argument: '
'%i argument(s) given' % len(args))
try:
feed = models.Feed.objects.get(pk=args[0])
except models.Feed.DoesNotExist:
raise CommandError('Feed with pk %s does not exist' % args[0])
try:
self.verbose = (int(options['verbosity']) > 1)
except (KeyError, ValueError):
self.verbose = False
httplib2 = eventlet.import_patched('httplib2')
# Use httplib2 to GET the feed.
# This permits us to download it only once, passing a parsed_feed through
# to the vidscraper functions.
h = httplib2.Http(DEFAULT_HTTPLIB_CACHE_PATH)
response, content = h.request(feed.feed_url, 'GET')
parsed_feed = feedparser.parse(content)
# Try to work asynchronously, calling feedparser ourselves. We can do that
# if the importer supports bulk_import_url_list.
feed_urls = bulk_import_url_list(parsed_feed=parsed_feed)
if type(feed_urls) != list: # hack.
return self.use_old_bulk_import(parsed_feed, feed)
else:
video_ids = self.bulk_import_asynchronously(parsed_feed, h, feed_urls, feed)
self.enqueue_celery_tasks_for_thumbnail_fetches(video_ids)
@transaction.commit_on_success
def bulk_import_asynchronously(self, original_parsed_feed, h, feed_urls, feed):
# This asynchronous bulk_import is a parallelism monster.
# We do as much network I/O as we can using eventlet,
# rather than threads or subprocesses.
httplib2 = eventlet.import_patched('httplib2')
httppool = eventlet.pools.Pool(max_size=200)
httppool.create = lambda: httplib2.Http(DEFAULT_HTTPLIB_CACHE_PATH)
pool = eventlet.GreenPool(100)
def get_url(url):
with httppool.item() as http:
if self.verbose:
print 'getting', url
resp, content = http.request(url, 'GET')
return (resp, content)
def cache_thumbnail_url(url):
with httppool.item() as http:
if self.verbose:
print 'getting thumb', url
localtv.util.cache_downloaded_file(url, http)
stats = {
'total': 0,
'imported': 0,
'skipped': 0
}
def handle_one_sub_feed(feed_contents):
parsed_feed = feedparser.parse(feed_contents)
# For each feed entry in this small sub-feed, handle the item.
for index, entry in enumerate(parsed_feed['entries'][::-1]):
yield handle_one_item(index, parsed_feed, entry)
def handle_one_item(index, parsed_feed, entry):
i = feed._handle_one_bulk_import_feed_entry(index, parsed_feed, entry, verbose=self.verbose, clear_rejected=False,
actually_save_thumbnails=False)
# Enqueue the work to download the thumbnail
if i['video']:
v = i['video']
thumbnail_url = v.thumbnail_url
if thumbnail_url:
cache_thumbnail_url(thumbnail_url)
stats['total'] += 1
if i['video'] is not None:
stats['imported'] += 1
else:
stats['skipped'] += 1
return i
results = []
for (response, content) in pool.imap(get_url, feed_urls):
result = handle_one_sub_feed(content)
results.extend(result)
# Get all the thumbnail URLs, and once you have them
pool.waitall() # wait for the thumbnails
# Finish marking the Feed as imported.
feed._mark_bulk_import_as_done(original_parsed_feed)
feed.status = models.FEED_STATUS_ACTIVE
feed.save()
print simplejson.dumps(stats),
return [i['video'].id for i in results if i['video']]
def enqueue_celery_tasks_for_thumbnail_fetches(self, video_ids):
if self.verbose:
print 'Starting thumbnail fetches for', video_ids
celery_tasks = []
for video_id in video_ids:
mod = import_module(settings.SETTINGS_MODULE)
manage_py = os.path.join(
os.path.dirname(mod.__file__),
'manage.py')
task = localtv.tasks.check_call.delay((
getattr(settings, 'PYTHON_EXECUTABLE', sys.executable),
manage_py,
'update_one_thumbnail',
video_id))
celery_tasks.append(task)
# FIXME: Wait for them all to finish
if self.verbose > 1:
print 'Finished thumbnail fetches.'
return
def use_old_bulk_import(self, parsed_feed, feed):
bulk_feed = bulk_import(feed_url=None, parsed_feed=parsed_feed)
stats = {
'total': 0,
'imported': 0,
'skipped': 0
}
try:
for i in feed._update_items_generator(verbose=self.verbose,
parsed_feed=bulk_feed,
clear_rejected=True,
actually_save_thumbnails=True):
if not models.Feed.objects.filter(pk=feed.pk).count():
# someone deleted the feed, quit
break
stats['total'] += 1
if i['video'] is not None:
stats['imported'] += 1
else:
stats['skipped'] += 1
finally:
feed.status = models.FEED_STATUS_ACTIVE
feed.save()
print simplejson.dumps(stats),
|
Python
| 0.000001
|
@@ -926,55 +926,8 @@
ion%0A
-from django.core.files.base import ContentFile%0A
from
|
502ffa8fe93e0066f3553039493ef8b552069141
|
Add KDumpConf shared mapper.
|
falafel/mappers/kdump.py
|
falafel/mappers/kdump.py
|
import re
from falafel.core.plugins import mapper
@mapper("cmdline")
def crashkernel_enabled(context):
"""
Determine if kernel is configured to reserve memory for the crashkernel
"""
for line in context.content:
if 'crashkernel' in line:
return True
@mapper("systemctl_list-unit-files")
@mapper("chkconfig")
def kdump_service_enabled(context):
"""
Determine if kdump service is enabled with system
RHEL5/6 uses chkconfig and if enabled will look something like this:
kdump 0:off 1:off 2:off 3:on 4:on 5:on 6:off
RHEL7 uses systemctl list-unit-files and if enabled will look like this:
kdump.service enabled
"""
for line in context.content:
if line.startswith('kdump') and ('on' in line or 'enabled' in line):
return True
@mapper("kdump.conf")
def kdump_using_local_disk(context):
"""
Determine if kdump service is using local disk
"""
KDUMP_NETWORK_REGEX = re.compile(r'^\s*(ssh|nfs4?|net)\s+', re.I)
KDUMP_LOCAL_DISK_REGEX = re.compile(r'^\s*(ext[234]|raw|xfs|btrfs|minix)\s+', re.I)
local_disk = True
for line in context.content:
if line.startswith('#') or line == '':
continue
elif KDUMP_NETWORK_REGEX.search(line):
local_disk = False
elif KDUMP_LOCAL_DISK_REGEX.search(line):
local_disk = True
return local_disk
|
Python
| 0
|
@@ -3,16 +3,64 @@
port re%0A
+from falafel.core import computed, MapperOutput%0A
from fal
@@ -91,16 +91,16 @@
mapper%0A
-
%0A%0A@mappe
@@ -839,16 +839,17 @@
) and ('
+:
on' in l
@@ -893,32 +893,856 @@
return True%0A%0A%0A
+@mapper(%22kdump.conf%22)%0Aclass KDumpConf(MapperOutput):%0A%0A @staticmethod%0A def parse_content(content):%0A data = %7B%7D%0A for line in content:%0A line = line.strip()%0A if not line or line.startswith('#'):%0A continue%0A k, v = line.split(' ', 1)%0A data%5Bk.strip()%5D = v.strip()%0A return data%0A%0A @computed%0A def using_local_disk(self):%0A KDUMP_NETWORK_REGEX = re.compile(r'%5E%5Cs*(ssh%7Cnfs4?%7Cnet)%5Cs+', re.I)%0A KDUMP_LOCAL_DISK_REGEX = re.compile(r'%5E%5Cs*(ext%5B234%5D%7Craw%7Cxfs%7Cbtrfs%7Cminix)%5Cs+', re.I)%0A local_disk = True%0A for k in self.data.keys():%0A if KDUMP_NETWORK_REGEX.search(k):%0A local_disk = False%0A elif KDUMP_LOCAL_DISK_REGEX.search(k):%0A local_disk = True%0A%0A return local_disk%0A%0A%0A
@mapper(%22kdump.c
|
4bce4da138c4dc8060e11451eb21fb2f7c0891f5
|
Fix issue #1: Runserver failed when having callback function in root URLconf
|
quickadmin/register.py
|
quickadmin/register.py
|
from django.contrib import admin
from django.utils.module_loading import import_module
from django.db.models import get_models
from django.conf import settings
from django.conf.urls import include, url
from django.utils.log import getLogger
from .config import QADMIN_DEFAULT_EXCLUDES, USE_APPCONFIG
logger = getLogger(__name__)
EXCL_MODELS = len('.models')
def filter_models(exclude=None):
"""Returns all found models within this Django instance"""
# Get all the models from installed apps
model_list = []
if USE_APPCONFIG:
from django.apps import apps
found = apps.get_models()
else:
found = get_models()
# Exclude some models
excl_set = list(getattr(settings, 'QADMIN_EXCLUDES', []))
if getattr(settings, 'QADMIN_EXCLUDE_STOCK', True):
excl_set.extend(QADMIN_DEFAULT_EXCLUDES)
for model in found:
app_name = model.__module__[:-EXCL_MODELS]
full_name = '.'.join([app_name, model.__name__])
if full_name in excl_set or app_name in excl_set:
continue
model_list.append(model)
return model_list
def update_admin_urls():
"""Admin urls set have to be updated or all new registered models will
be shown as disabled in admin area"""
# Delete the old admin URLs
old_pattern = None
admin_regex = r'^admin/'
project_urls = import_module(settings.ROOT_URLCONF)
for url_item in project_urls.urlpatterns:
if url_item.app_name == 'admin':
old_pattern = url_item
admin_regex = url_item.regex.pattern
project_urls.urlpatterns.remove(url_item)
break
# Reload updated admin URLs
try:
admin.autodiscover()
project_urls.urlpatterns.append(
url(admin_regex, include(admin.site.urls))
)
except:
logger.error('Error when updating new admin urls.')
if old_pattern:
project_urls.urlpatterns.append(old_pattern)
def register_models():
"""Register all models insde specific application"""
for model in filter_models():
try:
admin.site.register(model)
except admin.sites.AlreadyRegistered:
logger.error('The model "%s" is already registered' %
model.__name__)
update_admin_urls()
|
Python
| 0.000001
|
@@ -1441,16 +1441,33 @@
tterns:%0A
+ try:%0A
@@ -1507,24 +1507,28 @@
+
old_pattern
@@ -1546,24 +1546,28 @@
+
+
admin_regex
@@ -1591,16 +1591,20 @@
pattern%0A
+
@@ -1665,14 +1665,172 @@
+
break%0A
+ except AttributeError:%0A # Bypass the non-admin URLconf%0A logger.error('Error when finding and removing old admin URLconf.')%0A%0A
@@ -2065,19 +2065,23 @@
w admin
-url
+URLconf
s.')%0A
|
3efd6e00859afd4f8b875ab0d74e937a172f887a
|
Fix formatting in fedmsg-tweet log.
|
fedmsg/commands/tweet.py
|
fedmsg/commands/tweet.py
|
# This file is part of fedmsg.
# Copyright (C) 2012 Red Hat, Inc.
#
# fedmsg 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 2.1 of the License, or (at your option) any later version.
#
# fedmsg 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with fedmsg; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors: Ralph Bean <rbean@redhat.com>
#
import time
import twitter as twitter_api
import bitlyapi
import fedmsg
import fedmsg.meta
from fedmsg.commands import BaseCommand
class TweetCommand(BaseCommand):
""" Rebroadcast messages to twitter and statusnet
New values in the fedmsg configuration are needed for this to work. Lists
and dicts of authentication credentials such as:
- :term:`tweet_endpoints`
- :term:`bitly_settings`
And scalars to help with rate limiting such as:
- :term:`tweet_hibernate_duration`
- :term:`tweet_intermessage_pause`
"""
name = "fedmsg-tweet"
extra_args = []
daemonizable = True
def run(self):
# First, sanity checking.
if not self.config.get('tweet_endpoints', None):
raise ValueError("Not configured to tweet.")
# Boilerplate..
self.config['publish_endpoint'] = None
self.config['name'] = 'relay_inbound'
self.config['mute'] = True
# Set up fedmsg
fedmsg.init(**self.config)
fedmsg.meta.make_processors(**self.config)
# Set up twitter and statusnet.. multiple accounts if configured
settings = self.config.get('tweet_endpoints', [])
apis = [twitter_api.Api(**endpoint) for endpoint in settings]
# Set up bitly
settings = self.config['bitly_settings']
bitly = bitlyapi.BitLy(
settings['api_user'],
settings['api_key'],
)
# How long to sleep if we spew too fast.
hibernate_duration = self.config['tweet_hibernate_duration']
# Sleep a second or two inbetween messages to try and avoid the hibernate
intermessage_pause = self.config['tweet_intermessage_pause']
def _post_to_api(api, message):
try:
api.PostUpdate(message)
except Exception as e:
if 'Too many notices too fast;' in str(e):
# Cool our heels then try again.
self.log.info("Sleeping for %i", hibernate_duration)
time.sleep(hibernate_duration)
_post_to_api(api, message)
elif 'json decoding' in str(e):
# Let it slide ... no idea what this one is.
pass
elif 'duplicate' in str(e):
# Let it slide ...
pass
else:
raise
for name, ep, topic, msg in fedmsg.tail_messages(**self.config):
message = fedmsg.meta.msg2subtitle(msg, **self.config)
link = fedmsg.meta.msg2link(msg, **self.config)
if link:
link = bitly.shorten(longUrl=link)['url']
message = message[:138 - len(link)] + " " + link
else:
message = message[:140]
if not message:
self.log.info("Not tweeting blank message.")
continue
self.log.info("Tweeting %r" % message)
for api in apis:
_post_to_api(api, message)
time.sleep(intermessage_pause)
def tweet():
command = TweetCommand()
command.execute()
|
Python
| 0.000008
|
@@ -2840,17 +2840,18 @@
for %25i%22
-,
+ %25
hiberna
|
8d45b1f4b25d7f97e74429822a39b5906e65f775
|
Fix createdb AttributeError.
|
filebrowser_safe/base.py
|
filebrowser_safe/base.py
|
from __future__ import unicode_literals
# coding: utf-8
import os
import datetime
import time
import mimetypes
from django.core.files.storage import default_storage
from django.db.models.fields.files import FieldFile
from django.utils.encoding import smart_str
from django.utils.functional import cached_property
try:
from django.utils.encoding import smart_text
except ImportError:
# Backward compatibility for Py2 and Django < 1.5
from django.utils.encoding import smart_unicode as smart_text
from filebrowser_safe.functions import get_file_type, path_strip, get_directory
class FileObjectAPI(object):
""" A mixin class providing file properties. """
def __init__(self, path):
self.head = os.path.dirname(path)
self.filename = os.path.basename(path)
self.filename_lower = self.filename.lower()
self.filename_root, self.extension = os.path.splitext(self.filename)
self.mimetype = mimetypes.guess_type(self.filename)
def __str__(self):
return smart_str(self.path)
def __unicode__(self):
return smart_text(self.path)
def __repr__(self):
return smart_str("<%s: %s>" % (
self.__class__.__name__, self or "None"))
def __len__(self):
return len(self.path)
# GENERAL ATTRIBUTES
@cached_property
def filetype(self):
if self.is_folder:
return 'Folder'
return get_file_type(self.filename)
@cached_property
def filesize(self):
if self.exists:
return default_storage.size(self.path)
return None
@cached_property
def date(self):
if self.exists:
return time.mktime(
default_storage.modified_time(self.path).timetuple())
return None
@property
def datetime(self):
if self.date:
return datetime.datetime.fromtimestamp(self.date)
return None
@cached_property
def exists(self):
return default_storage.exists(self.path)
# PATH/URL ATTRIBUTES
@property
def path_relative_directory(self):
""" path relative to the path returned by get_directory() """
return path_strip(self.path, get_directory()).lstrip("/")
@property
def url(self):
return default_storage.url(self.path)
# FOLDER ATTRIBUTES
@property
def directory(self):
return path_strip(self.path, get_directory())
@property
def folder(self):
return os.path.dirname(
path_strip(os.path.join(self.head, ''), get_directory()))
@cached_property
def is_folder(self):
return default_storage.isdir(self.path)
@property
def is_empty(self):
if self.is_folder:
try:
dirs, files = default_storage.listdir(self.path)
except UnicodeDecodeError:
from mezzanine.core.exceptions import FileSystemEncodingChanged
raise FileSystemEncodingChanged()
if not dirs and not files:
return True
return False
def delete(self):
if self.is_folder:
default_storage.rmtree(self.path)
# shutil.rmtree(self.path)
else:
default_storage.delete(self.path)
def delete_versions(self):
for version in self.versions():
try:
default_storage.delete(version)
except:
pass
def delete_admin_versions(self):
for version in self.admin_versions():
try:
default_storage.delete(version)
except:
pass
class FileObject(FileObjectAPI):
"""
The FileObject represents a file (or directory) on the server.
An example::
from filebrowser.base import FileObject
fileobject = FileObject(path)
where path is a relative path to a storage location.
"""
def __init__(self, path):
self.path = path
super(FileObject, self).__init__(path)
@property
def name(self):
return self.path
class FieldFileObject(FieldFile, FileObjectAPI):
"""
Returned when a FileBrowseField is accessed on a model instance.
- Implements the FieldFile API so FileBrowseField can act as substitute for
django's built-in FileField.
- Implements the FileObject API for historical reasons.
"""
def __init__(self, instance, field, path):
FieldFile.__init__(self, instance, field, path)
FileObjectAPI.__init__(self, path)
|
Python
| 0
|
@@ -4522,14 +4522,20 @@
_(self, path
+ or ''
)%0A
|
38a8d47d3bd476f195d866e01b8a800ae86132e5
|
update battery script
|
files/bin/bin/battery.py
|
files/bin/bin/battery.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################################################
#
# battery
# -------
#
# This script will output a specific icon based on the charge of a laptop
# battery. When the script is run on a system without a battery it will
# output an icon accordingly.
#
# Additionally the script will send a notification to disconnect or connect
# the charger when it's above 80% or below 40%.
# (https://superuser.com/a/427108)
#
# Dependencies: python3, acpi, notify-send, font-awesome
#
# :authors: J.P.H. Bruins Slot
# :date: 24-04-2017
# :version: 0.1.0
#
##############################################################################
import os
import re
import sys
import subprocess
from pathlib import Path
FILE = "/tmp/bat"
def notify(percentage):
touch_file = os.path.isfile(FILE)
if percentage > 80 and not touch_file:
# notify and create file
subprocess.run(
[
"notify-send",
"-i",
"battery",
"Please disconnect charger"
]
)
Path(FILE).touch()
elif 40 <= percentage <= 80 and touch_file:
# remove touch file
os.remove(FILE)
elif percentage < 40 and not touch_file:
# notify and create file
subprocess.run(
[
"notify-send",
"-i",
"battery",
"Please connect charger"
]
)
Path(FILE).touch()
else:
pass
def check_status(metric_status):
if metric_status == b"Full":
return "✔"
elif metric_status == b"Charging":
return "⚡"
elif metric_status == b"Discharging":
return "⇣"
else:
return "?"
def main():
try:
console_output = subprocess.check_output(
"acpi",
stderr=subprocess.STDOUT,
shell=True)
except:
sys.exit(
"acpi not found please install with sudo apt-get install acpi")
# There is no battery and probably on a power supply
if b"No support" in console_output or console_output == "":
print("🔌")
return
# Format will be:
# Battery 1: discharging, 44%, 00:18:48 remaining
list_metrics = console_output.split(b", ")
metric_status = list_metrics[0].split(b":")[-1].strip()
metric_percentage = int(re.match(b'\d+', list_metrics[1]).group())
notify(metric_percentage)
print("%s %s%%" % (check_status(metric_status), metric_percentage))
if __name__ == '__main__':
main()
|
Python
| 0.000001
|
@@ -1565,32 +1565,51 @@
ef check_status(
+metric_percentage,
metric_status):%0A
@@ -1608,16 +1608,17 @@
tatus):%0A
+%0A
if m
@@ -1662,9 +1662,9 @@
rn %22
-%E2%9C%94
+%EF%80%8C
%22%0A
@@ -1720,9 +1720,9 @@
rn %22
-%E2%9A%A1
+%EF%83%A7
%22%0A
@@ -1773,17 +1773,326 @@
-return %22%E2%87%A3
+if metric_percentage %3C= 20:%0A return %22%EF%89%84%22%0A elif 21 %3C= metric_percentage %3C= 40:%0A return %22%EF%89%83%22%0A elif 41 %3C= metric_percentage %3C= 60:%0A return %22%EF%89%82%22%0A elif 61 %3C= metric_percentage %3C= 80:%0A return %22%EF%89%81%22%0A elif 81 %3C= metric_percentage %3C= 100:%0A return %22%EF%89%80
%22%0A
@@ -2119,9 +2119,9 @@
rn %22
-?
+%EF%84%A8
%22%0A%0A%0A
@@ -2520,9 +2520,9 @@
nt(%22
-%F0%9F%94%8C
+%EF%87%A6
%22)%0A
@@ -2800,87 +2800,212 @@
-notify(metric_percentage)%0A%0A print(%22%25s %25s%25%25%22 %25 (check_status(metric_status),
+# Send notification when necessary%0A notify(metric_percentage)%0A%0A print(%0A %22%7Bicon%7D %7Bpercentage%7D%25%22.format(%0A icon=check_status(metric_percentage, metric_status),%0A percentage=
metr
@@ -3017,17 +3017,31 @@
rcentage
-)
+%0A )%0A
)%0A%0A%0Aif _
|
e191a1a52360f78fd65f65727e07695002d0cb77
|
Convert PostArchiveAll to use paginate function.
|
firmant/writers/posts.py
|
firmant/writers/posts.py
|
# Copyright (c) 2010, Robert Escriva
# 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 list of conditions and the following disclaimer.
# * 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 Firmant 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"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT 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 IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from copy import copy
from firmant.writers import Writer
class PostArchiveAll(Writer):
'''Parse the posts into a list, grouped by page.
The :func:``render`` function should be overrridden to actually render the
posts.
This depends upon the objs having a value for the key ``posts``.
'''
def __init__(self, settings, objs):
Writer.__init__(self, settings, objs)
if settings.ENTRIES_PER_PAGE < 1:
raise ValueError('ENTRIES_PER_PAGE must be a positive value.')
def write(self):
'''Write the parsed posts to the filesystem.
Example on testdata/pristine::
>>> from pysettings.settings import Settings
>>> from firmant.application import Firmant
>>> s = {'PARSERS': {'posts': 'firmant.parsers.posts.PostParser'}
... ,'CONTENT_ROOT': 'testdata/pristine'
... ,'POSTS_SUBDIR': 'posts'
... ,'REST_EXTENSION': 'rst'
... ,'ENTRIES_PER_PAGE': 2
... }
>>> s = Settings(s)
>>> f = Firmant(s)
>>> f.parse()
>>> eaa = PostArchiveAll(s, f.objs)
>>> eaa.write()
Page 0 1-2 of 3:
- 2010-02-02-newday2
- 2010-02-02-newday
Page 1 3-4 of 3:
- 2010-02-01-newmonth
- 2010-01-01-newyear
Page 2 5-5 of 3:
- 2009-12-31-party
'''
per_page = self.settings.ENTRIES_PER_PAGE
posts = copy(self.objs['posts'])
posts.sort(key=lambda p: (p.published.date(), p.slug), reverse=True)
num_pages = (len(posts) + per_page - 1) / per_page
for page in range((len(posts) + per_page - 1) / per_page):
begin = page * per_page
end = begin + per_page
page_posts = posts[begin:end]
begin += 1
end = begin + len(page_posts) - 1
self.render(page, num_pages, begin, end, page_posts)
def render(self, page, num_pages, first, last, posts):
'''Render the function.
This should be overridden in base classes.
'''
print 'Page %i %i-%i of %i:' % (page, first, last, num_pages)
for post in posts:
s = post.published.strftime(' - %Y-%m-%d-%%s')
print s % post.slug
|
Python
| 0
|
@@ -1573,16 +1573,54 @@
t copy%0A%0A
+from firmant.paginate import paginate%0A
from fir
@@ -2750,17 +2750,17 @@
Page
-0
+1
1-2 of
@@ -2836,17 +2836,17 @@
Page
-1
+2
3-4 of
@@ -2924,17 +2924,17 @@
Page
-2
+3
5-5 of
@@ -3160,311 +3160,76 @@
-num_pages = (len(posts) + per_page - 1) / per_page%0A for page in range((len(posts) + per_page - 1) / per_page):%0A begin = page * per_page%0A end = begin + per_page%0A page_posts = posts%5Bbegin:end%5D%0A begin += 1%0A end = begin + len(
+for page, num_pages, begin, end, posts in paginate(per_
page
-_
+,
posts)
- - 1
+:
%0A
@@ -3282,13 +3282,8 @@
nd,
-page_
post
|
1cc8161fbbcf6c0994af1cd4d0b4bcc6ba2fe47f
|
Set message
|
bluebottle/activities/permissions.py
|
bluebottle/activities/permissions.py
|
from rest_framework import permissions
from bluebottle.activities.models import Activity
from bluebottle.initiatives.models import InitiativePlatformSettings
from bluebottle.utils.permissions import ResourcePermission, ResourceOwnerPermission, BasePermission
class ActivityOwnerPermission(ResourceOwnerPermission):
def has_object_action_permission(self, action, user, obj):
try:
owner = obj.owner
except Activity.owner.RelatedObjectDoesNotExist:
owner = None
is_owner = user in [
owner,
obj.initiative.owner,
] or user in obj.initiative.activity_managers.all()
if action == 'POST':
return is_owner or (obj.initiative.status == 'approved' and obj.initiative.is_open)
else:
return is_owner
class ActivityTypePermission(ResourcePermission):
def has_permission(self, request, view):
(settings, _) = InitiativePlatformSettings.objects.get_or_create()
if request.method == 'POST':
activity_type = view.model.__name__.lower()
if activity_type == 'collectactivity':
activity_type = 'collect'
return activity_type in settings.activity_types
return True
class ActivityStatusPermission(ResourcePermission):
def has_object_action_permission(self, action, user, obj):
if (
action in ('PATCH', 'PUT') and
obj.status in ('rejected', 'deleted')
):
return False
else:
return True
def has_action_permission(self, action, user, model_cls):
return True
class ActivitySegmentPermission(BasePermission):
code = "closed_segment"
def has_object_action_permission(self, action, user, obj):
self.message = None
activity_segments = obj.segments.filter(closed=True)
if activity_segments:
self.message = activity_segments.first().id
if not user.is_authenticated:
return False
if any(
segment in activity_segments for segment in user.segments.filter(closed=True)
):
return True
else:
return False
else:
return True
def has_action_permission(self, action, user, model_cls):
return True
class ContributorPermission(ResourcePermission):
perms_map = {
'GET': ['%(app_label)s.api_read_%(model_name)s'],
'OPTIONS': [],
'HEAD': ['%(app_label)s.api_read_%(model_name)s'],
'POST': ['%(app_label)s.api_add_own_%(model_name)s'],
'PUT': ['%(app_label)s.api_change_own_%(model_name)s'],
'PATCH': ['%(app_label)s.api_change_own_%(model_name)s'],
'DELETE': ['%(app_label)s.api_delete_own_%(model_name)s'],
}
def has_object_action_permission(self, action, user, obj):
perms = self.get_required_permissions(action, obj.__class__)
if action in permissions.SAFE_METHODS:
return user.has_perms(perms)
else:
return user.has_perms(perms) and user in [
obj.activity.owner,
obj.activity.initiative.owner,
] or user in obj.activity.initiative.activity_managers.all()
class ContributionPermission(ResourcePermission):
def has_action_permission(self, action, user, model_cls):
return True
def has_object_action_permission(self, action, user, obj):
return user in [
obj.contributor.activity.owner,
obj.contributor.activity.initiative.owner,
] or user in obj.contributor.activity.initiative.activity_managers.all()
class DeleteActivityPermission(ResourcePermission):
def has_object_action_permission(self, action, user, obj):
if (
action == 'DELETE' and
obj.status not in ('draft', 'needs_work', )
):
return False
else:
return True
def has_action_permission(self, action, user, model_cls):
return True
|
Python
| 0.000002
|
@@ -1709,16 +1709,35 @@
segment%22
+%0A message = None
%0A%0A de
|
bcb2f4677f0fd767cb3c638200398bd08a42d8b7
|
Fix for issue #112
|
lib/modules/management/runas.py
|
lib/modules/management/runas.py
|
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-RunAs',
'Author': ['rvrsh3ll (@424f424f)'],
'Description': ('Runas knockoff. Will bypass GPO path restrictions.'),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : True,
'MinPSVersion' : '2',
'Comments': [
'https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/RunAs.ps1'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
},
'CredID' : {
'Description' : 'CredID from the store to use.',
'Required' : False,
'Value' : ''
},
'Domain' : {
'Description' : 'Optional domain.',
'Required' : False,
'Value' : ''
},
'UserName' : {
'Description' : 'Username to run the command as.',
'Required' : False,
'Value' : ''
},
'Password' : {
'Description' : 'Password for the specified username.',
'Required' : False,
'Value' : ''
},
'Cmd' : {
'Description' : 'Command to run.',
'Required' : True,
'Value' : 'notepad.exe'
},
'ShowWindow' : {
'Description' : 'Switch. Show the window for the created process instead of hiding it.',
'Required' : False,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
# read in the common powerup.ps1 module source code
moduleSource = self.mainMenu.installPath + "/data/module_source/management/Invoke-RunAs.ps1"
try:
f = open(moduleSource, 'r')
except:
print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
return ""
script = f.read()
f.close()
script += "\nInvoke-RunAs "
# if a credential ID is specified, try to parse
credID = self.options["CredID"]['Value']
if credID != "":
if not self.mainMenu.credentials.is_credential_valid(credID):
print helpers.color("[!] CredID is invalid!")
return ""
(credID, credType, domainName, userName, password, host, sid, notes) = self.mainMenu.credentials.get_credentials(credID)[0]
if credType != "plaintext":
print helpers.color("[!] A CredID with a plaintext password must be used!")
return ""
if domainName != "":
self.options["Domain"]['Value'] = domainName
if userName != "":
self.options["UserName"]['Value'] = userName
if password != "":
self.options["Password"]['Value'] = password
if self.options["DomainName"]['Value'] == "" or self.options["UserName"]['Value'] == "" or self.options["Password"]['Value'] == "":
print helpers.color("[!] DomainName/UserName/Password or CredID required!")
return ""
for option,values in self.options.iteritems():
if option.lower() != "agent" and option.lower() != "credid":
if values['Value'] and values['Value'] != '':
if values['Value'].lower() == "true":
# if we're just adding a switch
script += " -" + str(option)
else:
script += " -" + str(option) + " " + str(values['Value'])
return script
|
Python
| 0
|
@@ -3973,20 +3973,16 @@
%5B%22Domain
-Name
%22%5D%5B'Valu
@@ -4121,20 +4121,16 @@
%5D Domain
-Name
/UserNam
|
ff90958a0c79936d5056840ba03a5863bcdef099
|
Mark as test as "todo" for now.
|
formal/test/test_util.py
|
formal/test/test_util.py
|
from twisted.trial import unittest
from formal import util
class TestUtil(unittest.TestCase):
def test_validIdentifier(self):
self.assertEquals(util.validIdentifier('foo'), True)
self.assertEquals(util.validIdentifier('_foo'), True)
self.assertEquals(util.validIdentifier('_foo_'), True)
self.assertEquals(util.validIdentifier('foo2'), True)
self.assertEquals(util.validIdentifier('Foo'), True)
self.assertEquals(util.validIdentifier(' foo'), False)
self.assertEquals(util.validIdentifier('foo '), False)
self.assertEquals(util.validIdentifier('9'), False)
|
Python
| 0
|
@@ -613,16 +613,84 @@
er('9'), False)%0A
+ test_validIdentifier.todo = %22Fails due to weird import poblem%22%0A%0A
|
03731136b6f2147ded54ce2881eddc4b1dba5d83
|
fix missing check for None
|
bumblebee_status/modules/core/nic.py
|
bumblebee_status/modules/core/nic.py
|
# pylint: disable=C0111,R0903
"""Displays the name, IP address(es) and status of each available network interface.
Requires the following python module:
* netifaces
Requires the following executable:
* iw
* (until and including 2.0.5: iwgetid)
Parameters:
* nic.exclude: Comma-separated list of interface prefixes (supporting regular expressions) to exclude (defaults to 'lo,virbr,docker,vboxnet,veth,br,.*:avahi')
* nic.include: Comma-separated list of interfaces to include
* nic.states: Comma-separated list of states to show (prefix with '^' to invert - i.e. ^down -> show all devices that are not in state down)
* nic.format: Format string (defaults to '{intf} {state} {ip} {ssid} {strength}')
* nic.strength_warning: Integer to set the threshold for warning state (defaults to 50)
* nic.strength_critical: Integer to set the threshold for critical state (defaults to 30)
"""
import re
import shutil
import netifaces
import subprocess
import core.module
import core.decorators
import util.cli
import util.format
class Module(core.module.Module):
@core.decorators.every(seconds=5)
def __init__(self, config, theme):
widgets = []
super().__init__(config, theme, widgets)
self._exclude = util.format.aslist(
self.parameter("exclude", "lo,virbr,docker,vboxnet,veth,br,.*:avahi")
)
self._include = util.format.aslist(self.parameter("include", ""))
self._states = {"include": [], "exclude": []}
for state in tuple(
filter(len, util.format.aslist(self.parameter("states", "")))
):
if state[0] == "^":
self._states["exclude"].append(state[1:])
else:
self._states["include"].append(state)
self._format = self.parameter("format", "{intf} {state} {ip} {ssid} {strength}")
self._strength_threshold_critical = self.parameter("strength_critical", 30)
self._strength_threshold_warning = self.parameter("strength_warning", 50)
# Limits for the accepted dBm values of wifi strength
self.__strength_dbm_lower_bound = -110
self.__strength_dbm_upper_bound = -30
self.iw = shutil.which("iw")
self._update_widgets(widgets)
def update(self):
self._update_widgets(self.widgets())
def state(self, widget):
states = []
if widget.get("state") == "down":
states.append("critical")
elif widget.get("state") != "up":
states.append("warning")
intf = widget.get("intf")
iftype = "wireless" if self._iswlan(intf) else "wired"
iftype = "tunnel" if self._istunnel(intf) else iftype
# "strength" is none if interface type is not wlan
if self._iswlan(intf):
if widget.get("strength") < self._strength_threshold_critical:
states.append("critical")
elif widget.get("strength") < self._strength_threshold_warning:
states.append("warning")
states.append("{}-{}".format(iftype, widget.get("state")))
return states
def _iswlan(self, intf):
# wifi, wlan, wlp, seems to work for me
if intf.startswith("w"):
return True
return False
def _istunnel(self, intf):
return intf.startswith("tun") or intf.startswith("wg")
def get_addresses(self, intf):
retval = []
try:
for ip in netifaces.ifaddresses(intf).get(netifaces.AF_INET, []):
if ip.get("addr", "") != "":
retval.append(ip.get("addr"))
except Exception:
return []
return retval
def _excluded(self, intf):
for e in self._exclude:
if re.match(e, intf):
return True
return False
def _update_widgets(self, widgets):
self.clear_widgets()
interfaces = []
for i in netifaces.interfaces():
if not self._excluded(i):
interfaces.append(i)
interfaces.extend([i for i in netifaces.interfaces() if i in self._include])
for intf in interfaces:
addr = []
state = "down"
for ip in self.get_addresses(intf):
addr.append(ip)
state = "up"
if len(self._states["exclude"]) > 0 and state in self._states["exclude"]:
continue
if (
len(self._states["include"]) > 0
and state not in self._states["include"]
):
continue
strength_dbm = self.get_strength_dbm(intf)
strength_percent = self.convert_strength_dbm_percent(strength_dbm)
widget = self.widget(intf)
if not widget:
widget = self.add_widget(name=intf)
# join/split is used to get rid of multiple whitespaces (in case SSID is not available, for instance
widget.full_text(
" ".join(
self._format.format(
ip=", ".join(addr),
intf=intf,
state=state,
strength=str(strength_percent) + "%" if strength_percent else "",
ssid=self.get_ssid(intf),
).split()
)
)
widget.set("intf", intf)
widget.set("state", state)
widget.set("strength", strength_percent)
def get_ssid(self, intf):
if not self._iswlan(intf) or self._istunnel(intf) or not self.iw:
return ""
iw_info = util.cli.execute("{} dev {} info".format(self.iw, intf))
for line in iw_info.split("\n"):
match = re.match(r"^\s+ssid\s(.+)$", line)
if match:
return match.group(1)
return ""
def get_strength_dbm(self, intf):
if not self._iswlan(intf) or self._istunnel(intf) or not self.iw:
return None
with open("/proc/net/wireless", "r") as file:
for line in file:
if intf in line:
# Remove trailing . by slicing it off ;)
strength_dbm = line.split()[3][:-1]
return util.format.asint(strength_dbm,
minimum=self.__strength_dbm_lower_bound,
maximum=self.__strength_dbm_upper_bound)
return None
def convert_strength_dbm_percent(self, signal):
return int(100 * ((signal + 100) / 70.0)) if signal else None
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
Python
| 0.000016
|
@@ -2761,16 +2761,58 @@
ot wlan%0A
+ strength = widget.get(%22strength%22)%0A
@@ -2828,24 +2828,37 @@
iswlan(intf)
+ and strength
:%0A
@@ -2862,36 +2862,24 @@
if
-widget.get(%22
strength
%22) %3C sel
@@ -2862,34 +2862,32 @@
if strength
-%22)
%3C self._strengt
@@ -2967,36 +2967,24 @@
elif
-widget.get(%22
strength
%22) %3C sel
@@ -2975,18 +2975,16 @@
strength
-%22)
%3C self.
|
5163b23f5060e22aee64b2318fff19775ce68aed
|
Add unique constraints to FilingIDValue and FilerIDValue
|
calaccess_processed/models/common.py
|
calaccess_processed/models/common.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Models for storing general filer and filing data derived from raw CAL-ACCESS data.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from calaccess_processed.managers import ProcessedDataManager
@python_2_unicode_compatible
class FilerIDValue(models.Model):
"""
Every unique filer_id in the CAL-ACCESS database.
Includes the table and column in which the unique value was observed
"""
table_name = models.CharField(
verbose_name="table_name",
max_length=30,
db_index=True,
null=False,
blank=False,
help_text="Name of the database table with the column where the "
"filer_id value was observed.",
)
column_name = models.CharField(
verbose_name="column_name",
max_length=20,
null=False,
blank=False,
db_index=True,
help_text="Name of the database column where the filer_id value was "
"observed.",
)
value = models.CharField(
verbose_name="filer_id value",
max_length=15,
null=False,
blank=False,
db_index=True,
help_text="Unique filer_id value in the given database table and column.",
)
occur_count = models.IntegerField(
verbose_name="occurence count",
null=False,
db_index=True,
help_text="Count of occurences of the filer_id value in the given "
"database table and column.",
)
objects = ProcessedDataManager()
class Meta:
"""
Meta model options.
"""
app_label = 'calaccess_processed'
def __str__(self):
return str(self.value)
@python_2_unicode_compatible
class FilingIDValue(models.Model):
"""
Every unique filing_id in the CAL-ACCESS database.
Includes the table and column in which the unique value was observed
"""
table_name = models.CharField(
verbose_name="table_name",
max_length=30,
null=False,
blank=False,
db_index=True,
help_text="Name of the database table with the column where the "
"filing_id value was observed.",
)
value = models.IntegerField(
verbose_name="filing_id value",
null=False,
blank=False,
db_index=True,
help_text="Unique filing_id value in the given database table and column.",
)
occur_count = models.IntegerField(
verbose_name="occurence count",
null=False,
db_index=True,
help_text="Count of occurences of the filing_id value in the given "
"database table and column.",
)
objects = ProcessedDataManager()
class Meta:
"""
Meta model options.
"""
app_label = 'calaccess_processed'
def __str__(self):
return str(self.value)
|
Python
| 0
|
@@ -1730,32 +1730,100 @@
ccess_processed'
+%0A unique_together = (('table_name', 'column_name', 'value'),)
%0A%0A def __str_
@@ -2989,16 +2989,69 @@
ocessed'
+%0A unique_together = (('table_name', 'value'),)
%0A%0A de
|
ca39ed340043f1ddeca6fb82e32b2ed3d8971029
|
Update terrain_helper.py
|
cea/datamanagement/terrain_helper.py
|
cea/datamanagement/terrain_helper.py
|
"""
This script extracts terrain elevation from NASA - SRTM
https://www2.jpl.nasa.gov/srtm/
"""
from __future__ import division
from __future__ import print_function
import os
import gdal
import numpy as np
import pandas as pd
import requests
from geopandas import GeoDataFrame as Gdf
from osgeo import ogr
from osgeo import osr
from shapely.geometry import Polygon
import cea.config
import cea.inputlocator
from cea.utilities.standardize_coordinates import get_projected_coordinate_system, get_geographic_coordinate_system
__author__ = "Jimeno Fonseca"
__copyright__ = "Copyright 2018, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Jimeno Fonseca"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "cea@arch.ethz.ch"
__status__ = "Production"
def request_elevation(lon, lat):
# script for returning elevation from lat, long, based on open elevation data
# which in turn is based on SRTM
query = ('https://api.open-elevation.com/api/v1/lookup?locations=' + str(lat) + ',' + str(lon))
r = requests.get(query).json() # json object, various ways you can extract value
# one approach is to use pandas json functionality:
elevation = pd.io.json.json_normalize(r, 'results')['elevation'].values[0]
return elevation
def calc_bounding_box_projected_coordinates(shapefile_zone, shapefile_surroundings):
# connect both files and avoid repetition
data_zone = Gdf.from_file(shapefile_zone)
data_dis = Gdf.from_file(shapefile_surroundings)
data_dis = data_dis.loc[~data_dis["Name"].isin(data_zone["Name"])]
data = data_dis.append(data_zone, ignore_index = True, sort=True)
data = data.to_crs(get_geographic_coordinate_system())
lon = data.geometry[0].centroid.coords.xy[0][0]
lat = data.geometry[0].centroid.coords.xy[1][0]
crs = get_projected_coordinate_system(float(lat), float(lon))
data = data.to_crs(get_projected_coordinate_system(float(lat), float(lon)))
result = data.total_bounds
result = [np.float32(x) for x in result] # in float32 so the raster works
return result, crs, lon, lat
def terrain_elevation_extractor(locator, config):
"""this is where the action happens if it is more than a few lines in ``main``.
NOTE: ADD YOUR SCRIPT'S DOCUMENATION HERE (how)
NOTE: RENAME THIS FUNCTION (SHOULD PROBABLY BE THE SAME NAME AS THE MODULE)
"""
# local variables:
elevation = config.terrain_helper.elevation
grid_size = config.terrain_helper.grid_size
extra_border = np.float32(30) # adding extra 30 m to avoid errors of no data
raster_path = locator.get_terrain()
locator.ensure_parent_folder_exists(raster_path)
# get the bounding box coordinates
assert os.path.exists(
locator.get_surroundings_geometry()), 'Get surroundings geometry file first or the coordinates of the area where' \
' to extract the terrain from in the next format: lon_min, lat_min, lon_max, lat_max'
print("generating terrain from Surroundings area")
bounding_box_surroundings_file, crs, lon, lat = calc_bounding_box_projected_coordinates(locator.get_surroundings_geometry(), locator.get_zone_geometry())
x_min = bounding_box_surroundings_file[0] - extra_border
y_min = bounding_box_surroundings_file[1] - extra_border
x_max = bounding_box_surroundings_file[2] + extra_border
y_max = bounding_box_surroundings_file[3] + extra_border
# make sure output is a whole number when min-max is divided by grid size
x_extra = grid_size - ((x_max - x_min) % grid_size)/2
y_extra = grid_size - ((y_max - y_min) % grid_size)/2
x_min -= x_extra
y_min -= y_extra
x_max += x_extra
y_max += y_extra
##TODO: get the elevation from satellite data. Open-elevation was working, but the project is dying.
# if elevation is None:
# print('extracting elevation from satellite data, this needs connection to the internet')
# elevation = request_elevation(lon, lat)
# print("Proceeding to calculate terrain file with fixed elevation in m of ", elevation)
# else:
# print("Proceeding to calculate terrain file with fixed elevation in m of ",elevation)
print("Proceeding to calculate terrain file with fixed elevation in m of ", elevation)
# now calculate the raster with the fixed elevation
calc_raster_terrain_fixed_elevation(crs, elevation, grid_size, raster_path, locator,
x_max, x_min, y_max, y_min)
def calc_raster_terrain_fixed_elevation(crs, elevation, grid_size, raster_path, locator, x_max, x_min, y_max,
y_min):
# local variables:
temp_shapefile = locator.get_temporary_file("terrain.shp")
cols = int((x_max - x_min) / grid_size)
rows = int((y_max - y_min) / grid_size)
shapes = Polygon([[x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max], [x_min, y_min]])
geodataframe = Gdf(index=[0], crs=crs, geometry=[shapes])
geodataframe.to_file(temp_shapefile)
# 1) opening the shapefile
source_ds = ogr.Open(temp_shapefile)
source_layer = source_ds.GetLayer()
target_ds = gdal.GetDriverByName('GTiff').Create(raster_path, cols, rows, 1, gdal.GDT_Float32) ##COMMENT 2
target_ds.SetGeoTransform((x_min, grid_size, 0, y_max, 0, -grid_size)) ##COMMENT 3
# 5) Adding a spatial reference ##COMMENT 4
target_dsSRS = osr.SpatialReference()
target_dsSRS.ImportFromProj4(crs)
target_ds.SetProjection(target_dsSRS.ExportToWkt())
band = target_ds.GetRasterBand(1)
band.SetNoDataValue(-9999) ##COMMENT 5
gdal.RasterizeLayer(target_ds, [1], source_layer, burn_values=[elevation]) ##COMMENT 6
target_ds = None # closing the file
def main(config):
"""
This is the main entry point to your script. Any parameters used by your script must be present in the ``config``
parameter. The CLI will call this ``main`` function passing in a ``config`` object after adjusting the configuration
to reflect parameters passed on the command line - this is how the ArcGIS interface interacts with the scripts
BTW.
:param config:
:type config: cea.config.Configuration
:return:
"""
assert os.path.exists(config.scenario), 'Scenario not found: %s' % config.scenario
locator = cea.inputlocator.InputLocator(config.scenario)
terrain_elevation_extractor(locator, config)
if __name__ == '__main__':
main(cea.config.Configuration())
|
Python
| 0.000002
|
@@ -5823,366 +5823,35 @@
-This is the main entry point to your script. Any parameters used by your script must be present in the %60%60config%60%60%0A parameter. The CLI will call this %60%60main%60%60 function passing in a %60%60config%60%60 object after adjusting the configuration%0A to reflect parameters passed on the command line - this is how the ArcGIS interface interacts with the scripts%0A BTW.
+Create the terrain.tif file
%0A%0A
|
ca166f5eaec617eb56020a2349dc74dfa9bfcd57
|
verify behavior for single monitors in a cluster
|
ceph_medic/tests/checks/test_mons.py
|
ceph_medic/tests/checks/test_mons.py
|
from ceph_medic import metadata
from ceph_medic.checks import mons
class TestGetSecret(object):
def setup(self):
self.data = {
'paths': {
'/var/lib/ceph': {
'files': {
'/var/lib/ceph/mon/ceph-mon-0/keyring': {
'contents': '',
}
}
}
}
}
def set_contents(self, string, file_path=None):
file_path = file_path or '/var/lib/ceph/mon/ceph-mon-0/keyring'
self.data['paths']['/var/lib/ceph']['files'][file_path]['contents'] = string
def test_get_secret(self):
contents = """
[mon.]
key = AQBvaBFZAAAAABAA9VHgwCg3rWn8fMaX8KL01A==
caps mon = "allow *"
"""
self.set_contents(contents)
result = mons.get_secret(self.data)
assert result == 'AQBvaBFZAAAAABAA9VHgwCg3rWn8fMaX8KL01A=='
def test_get_no_secret_empty_file(self):
result = mons.get_secret(self.data)
assert result == ''
def test_get_no_secret_wrong_file(self):
contents = """
[mon.]
caps mon = "allow *"
"""
self.set_contents(contents)
result = mons.get_secret(self.data)
assert result == ''
class TestGetMonitorDirs(object):
def test_get_monitor_dirs(self):
result = mons.get_monitor_dirs([
'/var/lib/ceph/mon/ceph-mon-1',
'/var/lib/ceph/something'])
assert result == set(['ceph-mon-1'])
def test_cannot_get_monitor_dirs(self):
result = mons.get_monitor_dirs([
'/var/lib/ceph/osd/ceph-osd-1',
'/var/lib/ceph/something'])
assert result == set([])
def test_get_monitor_dirs_multiple(self):
result = mons.get_monitor_dirs([
'/var/lib/ceph/mon/ceph-mon-1',
'/var/lib/ceph/mon/ceph-mon-3',
'/var/lib/ceph/mon/ceph-mon-2',
'/var/lib/ceph/something'])
assert result == set(['ceph-mon-1', 'ceph-mon-2', 'ceph-mon-3'])
def test_get_monitor_dirs_nested_multiple(self):
result = mons.get_monitor_dirs([
'/var/lib/ceph/mon/ceph-mon-1',
'/var/lib/ceph/mon/ceph-mon-1/nested/dir/',
'/var/lib/ceph/mon/ceph-mon-1/other/nested',
'/var/lib/ceph/mon/ceph-mon-2',
'/var/lib/ceph/something'])
assert result == set(['ceph-mon-1', 'ceph-mon-2'])
class TestOsdDirs(object):
def test_get_osd_dirs_nested_multiple(self):
result = mons.get_osd_dirs([
'/var/lib/ceph/osd/ceph-1',
'/var/lib/ceph/osd/ceph-1/nested/dir/',
'/var/lib/ceph/osd/ceph-1/other/nested',
'/var/lib/ceph/osd/ceph-2',
'/var/lib/ceph/something'])
assert result == set(['ceph-1', 'ceph-2'])
class TestMonRecommendedCount(object):
def test_recommended_count_is_met(self, data):
metadata['mons'] = dict(('mon%s' % count, []) for count in range(6))
metadata['cluster_name'] = 'ceph'
osd_data = data()
result = mons.check_mon_recommended_count(None, osd_data)
assert result is None
def test_recommended_count_is_unmet(self, data):
metadata['mons'] = dict(('mon%s' % count, []) for count in range(1))
metadata['cluster_name'] = 'ceph'
osd_data = data()
code, message = mons.check_mon_recommended_count(None, osd_data)
assert code == 'WMON3'
assert message == 'Recommended number of MONs (3) not met: 1'
class TestMonCountIsOdd(object):
def test_count_is_odd(self, data):
metadata['mons'] = dict(('mon%s' % count, []) for count in range(3))
metadata['cluster_name'] = 'ceph'
osd_data = data()
result = mons.check_mon_count_is_odd(None, osd_data)
assert result is None
def test_recommended_count_is_unmet(self, data):
metadata['mons'] = dict(('mon%s' % count, []) for count in range(2))
metadata['cluster_name'] = 'ceph'
osd_data = data()
code, message = mons.check_mon_count_is_odd(None, osd_data)
assert code == 'WMON4'
assert message == 'Number of MONs is not an odd number: 2'
|
Python
| 0
|
@@ -4274,8 +4274,566 @@
ber: 2'%0A
+%0A%0Aclass TestSingleMon(object):%0A%0A def test_is_single(self, data):%0A metadata%5B'mons'%5D = %7B'mon.0': %5B%5D%7D%0A metadata%5B'cluster_name'%5D = 'ceph'%0A code, message = mons.check_for_single_mon(None, data())%0A assert code == 'WMON5'%0A assert message == 'A single monitor was detected: mon.0'%0A%0A def test_is_not_single(self, data):%0A metadata%5B'mons'%5D = dict(('mon%25s' %25 count, %5B%5D) for count in range(2))%0A metadata%5B'cluster_name'%5D = 'ceph'%0A result = mons.check_for_single_mon(None, data())%0A assert result is None%0A
|
2e7271a33e098d7cdef15207e8caa05e644c3223
|
Use full URI for build failure reasons
|
changes/buildfailures/testfailure.py
|
changes/buildfailures/testfailure.py
|
from __future__ import absolute_import
from jinja2 import Markup
from changes.buildfailures.base import BuildFailure
class TestFailure(BuildFailure):
def get_html_label(self, build):
link = '/projects/{0}/builds/{1}/tests/?result=failed'.format(build.project.slug, build.id.hex)
try:
test_failures = (
s.value for s in build.stats if s.name == 'test_failures'
).next()
except StopIteration:
return Markup('There were an <a href="{link}">unknown number of test failures</a>.'.format(
link=link,
))
return Markup('There were <a href="{link}">{count} failing tests</a>.'.format(
link=link,
count=test_failures,
))
|
Python
| 0
|
@@ -112,16 +112,57 @@
Failure%0A
+from changes.utils.http import build_uri%0A
%0A%0Aclass
@@ -240,16 +240,26 @@
link =
+build_uri(
'/projec
@@ -338,16 +338,17 @@
.id.hex)
+)
%0A%0A
|
b45114af06f5f339b2a70d5a26edea79a1725b01
|
Fix slot generator.
|
generate_custom_slots.py
|
generate_custom_slots.py
|
from kodi import Kodi
import re
import string
import random
config_file = os.path.join(os.path.dirname(__file__), "kodi.config")
config = KodiConfigParser(config_file)
kodi = Kodi(config)
# Generate MUSICARTISTS Slot
retrieved = kodi.GetMusicArtists()
all = []
if 'result' in retrieved and 'artists' in retrieved['result']:
for v in retrieved['result']['artists']:
name = kodi.sanitize_name(v['artist'])
name_stripped = kodi.sanitize_name(v['artist'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('MUSICARTISTS', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
# Generate MUSICALBUMS Slot
retrieved = kodi.GetAlbums()
all = []
if 'result' in retrieved and 'albums' in retrieved['result']:
for v in retrieved['result']['albums']:
name = kodi.sanitize_name(v['label'])
name_stripped = kodi.sanitize_name(v['label'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('MUSICALBUMS', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
# Generate MUSICSONGS Slot
retrieved = kodi.GetSongs()
all = []
if 'result' in retrieved and 'songs' in retrieved['result']:
for v in retrieved['result']['songs']:
name = kodi.sanitize_name(v['label'])
name_stripped = kodi.sanitize_name(v['label'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('MUSICSONGS', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
# Generate MUSICPLAYLISTS Slot
retrieved = kodi.GetMusicPlaylists()
all = []
if 'result' in retrieved and 'files' in retrieved['result']:
for v in retrieved['result']['files']:
name = kodi.sanitize_name(v['label'])
name_stripped = kodi.sanitize_name(v['label'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('MUSICPLAYLISTS', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
# Generate VIDEOPLAYLISTS Slot
retrieved = kodi.GetVideoPlaylists()
all = []
if 'result' in retrieved and 'files' in retrieved['result']:
for v in retrieved['result']['files']:
name = kodi.sanitize_name(v['label'])
name_stripped = kodi.sanitize_name(v['label'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('VIDEOPLAYLISTS', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
# Generate MOVIEGENRES Slot
retrieved = kodi.GetMovieGenres()
all = []
if 'result' in retrieved and 'genres' in retrieved['result']:
for v in retrieved['result']['genres']:
name = kodi.sanitize_name(v['label'])
name_stripped = kodi.sanitize_name(v['label'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('MOVIEGENRES', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
# Generate MOVIES Slot
retrieved = kodi.GetMovies()
all = []
if 'result' in retrieved and 'movies' in retrieved['result']:
for v in retrieved['result']['movies']:
name = kodi.sanitize_name(v['label'])
name_stripped = kodi.sanitize_name(v['label'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('MOVIES', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
# Generate SHOWS Slot
retrieved = kodi.GetTvShows()
all = []
if 'result' in retrieved and 'tvshows' in retrieved['result']:
for v in retrieved['result']['tvshows']:
name = kodi.sanitize_name(v['label'])
name_stripped = kodi.sanitize_name(v['label'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('SHOWS', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
# Generate ADDONS Slot
all = []
for content in ['video', 'audio', 'image', 'executable']:
retrieved = kodi.GetAddons(content)
if 'result' in retrieved and 'addons' in retrieved['result']:
for v in retrieved['result']['addons']:
name = kodi.sanitize_name(v['name'])
name_stripped = kodi.sanitize_name(v['name'], True)
all.append(name)
all.append(name_stripped)
cleaned = list(set(all))
cleaned = filter(None, cleaned)
random.shuffle(cleaned)
cleaned = cleaned[:300]
gfile = open('ADDONS', 'w')
for a in cleaned:
gfile.write("%s\n" % a)
gfile.close()
|
Python
| 0
|
@@ -1,25 +1,27 @@
-from kodi
+import re%0A
import
-Kodi
+string
%0Aimp
@@ -21,33 +21,37 @@
ing%0Aimport r
-e
+andom
%0Aimport
string%0Aimpor
@@ -38,36 +38,64 @@
%0Aimport
-string%0Aimport random
+os%0Afrom kodi_voice import KodiConfigParser, Kodi
%0A%0Aconfig
|
4c303007d6418e2a2f1b2e1778d6b7d0c0573c74
|
Raise read-only fs on touch
|
gitfs/views/read_only.py
|
gitfs/views/read_only.py
|
import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
raise FuseOSError(EROFS)
def write(self, path, fh):
raise FuseOSError(EROFS)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
return 0
def flush(self, path, fh):
return 0
def release(self, path, fh):
return 0
def access(self, path, amode):
return 0
def mkdir(self, path, mode):
raise FuseOSError(EROFS)
|
Python
| 0
|
@@ -1,14 +1,4 @@
-import os%0A
from
@@ -699,28 +699,103 @@
raise FuseOSError(EROFS)%0A
+%0A def utimens(self, path, times=None):%0A raise FuseOSError(EROFS)%0A
|
79acfd42a4c9eccc1d365412fca9186b568e4d6d
|
Fix performance for AssetForeignKey
|
glitter/assets/fields.py
|
glitter/assets/fields.py
|
from itertools import groupby
from django.db import models
from django.forms.models import ModelChoiceField, ModelChoiceIterator
class GroupedModelChoiceField(ModelChoiceField):
def __init__(self, queryset, group_by_field='category', group_label=None, *args, **kwargs):
"""
group_by_field is the name of a field on the model
group_label is a function to return a label for each choice group
"""
super().__init__(queryset, *args, **kwargs)
self.group_by_field = group_by_field
if group_label is None:
self.group_label = lambda group: group
else:
self.group_label = group_label
# Need correct ordering, and category titles
self.queryset = self.queryset.select_related().order_by('category', 'title')
def _get_choices(self):
"""
Exactly as per ModelChoiceField except returns new iterator class
"""
if hasattr(self, '_choices'):
return self._choices
return GroupedModelChoiceIterator(self)
choices = property(_get_choices, ModelChoiceField._set_choices)
class GroupedModelChoiceIterator(ModelChoiceIterator):
def __iter__(self):
if self.field.empty_label is not None:
yield ('', self.field.empty_label)
if hasattr(self.field, 'cache_choices') and self.field.cache_choices:
if self.field.choice_cache is None:
self.field.choice_cache = [
(self.field.group_label(group), [self.choice(ch) for ch in choices])
for group, choices in groupby(
self.queryset.all(), key=lambda row: getattr(
row, self.field.group_by_field
)
)
]
for choice in self.field.choice_cache:
yield choice
else:
for group, choices in groupby(
self.queryset.all(),
key=lambda row: getattr(row, self.field.group_by_field)
):
yield (self.field.group_label(group), [self.choice(ch) for ch in choices])
class AssetForeignKey(models.ForeignKey):
def formfield(self, **kwargs):
kwargs.setdefault('form_class', GroupedModelChoiceField)
return super().formfield(**kwargs)
|
Python
| 0
|
@@ -771,16 +771,26 @@
related(
+'category'
).order_
|
7c3a164b74f345be07843482728b2e0b33a927bc
|
bump minor version
|
src/graceful/__init__.py
|
src/graceful/__init__.py
|
# -*- coding: utf-8 -*-
VERSION = (0, 0, 4) # PEP 386 # noqa
__version__ = ".".join([str(x) for x in VERSION]) # noqa
"""
Minimalist framework for self-descriptive RESTful APIs build on top of
falcon.
It is inspired by Django REST Framework package. Mostly by how object
serialization is done but more emphasis is put on API to being
self-descriptive.
"""
|
Python
| 0
|
@@ -35,12 +35,12 @@
(0,
-0, 4
+1, 0
) #
|
fc15f0d36c4c0b32966845165445bba903a558ed
|
Update LinearEquationsSolver.py
|
LinearEquationsSolver.py
|
LinearEquationsSolver.py
|
#CS101 Project
#Linear equations solver using Gaussian elimination for equations with integer coefficients.
#Python 3.6
import sys, os
'''
The standard input textfile will contain an integer T in the first line, denoting the number of system of linear euations to be solved.
The first line of each test case will contain two numbers num_var and num_eq denoting the number of variables and number of equations.
The next num_eq lines will num_var+1 integers, denoting a equation of the form (a*x_1) + (b*x_2)=c, with a, b and c stored as values.
'''
def GCD(num_1, num_2):
if num_1==0:
return num_2
else:
return GCD(num_2%num_1, num_1)
#Class for rational numbers
class irreducibleFractions:
def update(self, num_1, num_2):
if num_1==0 or num_2==0:
self.num=0
self.deno=1
else:
sign=True
if num_1*num_2<0:
sign=False
if num_1<0:
num_1=-num_1
if num_2<0:
num_2=-num_2
g=GCD(num_1, num_2)
if not sign:
self.num=-(num_1//g)
self.deno=num_2//g
else:
self.num=num_1//g
self.deno=num_2//g
def __init__(self, num_1, num_2):
self.num=num_1
self.deno=num_2
self.update(num_1, num_2)
def __str__(self):
return str(self.num)+'/'+str(self.deno)
def getNum(self):
return self.num
def getDeno(self):
return self.deno
def equationSolver(sys_Eq, rows, cols):
#Converting the augmented matrix sys_Eq to row reduced echleon form
row=rows
col=cols+1 #Considering the augmented matrix.
#Row reducing to ehcelon form using Gaussian Elimination
for i in range(row):
for j in range(col):
if sys_Eq[i][j]!=0:
for y in range(row):
if y!=i:
coeff1=sys_Eq[y][j]
coeff2=sys_Eq[i][j]
for z in range(j, col):
sys_Eq[y][z]=coeff2*sys_Eq[y][z]-coeff1*sys_Eq[i][z]
break
fracObjs=[]
for i in range(row):
temp=[]
for j in range(col):
temp.append([])
fracObjs.append(temp)
for i in range(row):
for j in range(col):
if sys_Eq[i][j]!=0:
num_2=sys_Eq[i][j]
for j in range(col):
fracObjs[i][j]=irreducibleFractions(sys_Eq[i][j], num_2)
#Checking for consistency
for i in range(row):
for j in range(col):
if sys_Eq[i][j]!=0 and j==cols:
return [False]
elif sys_Eq[i][j]!=0 and j!=cols:
break
result=[]
for x in range(cols):
result.append('')
#Finding the values of num_var variables.
for i in range(row):
for j in range(cols):
if fracObjs[i][j].__str__()!='0/1':
for y in range(j+1, cols):
if fracObjs[i][y].__str__()!='0/1':
if result[j]!='':
result[j]+='+'
result[j]+='('+fracObjs[i][y].__str__()+' * x_'+str(y+1)+')'
if fracObjs[i][cols].__str__()!='0/1':
if result[j]!='':
result[j]+='+'
result[j]+='('+fracObjs[i][cols].__str__()+')'
break
return [True]+result
filename=''
try:
filename=sys.argv[1]
except:
while filename=='' or not os.path.exists(filename):
filename=input("Enter a valid input text filename:")
'''
The output file will be named as Result of [input_filename].
The output file for every test case will num_var lines if the system is consitent,
otherwise it will state that the given sytem is inconsistent.
If the system is consitent, ith of num_var lines will hold the value of x_ith variable.
If x_ith variable is a free variable, it will x_ith is free.
'''
#Reading Input from the text file.
with open(filename, 'r') as ifile:
inp=ifile.readlines()
wfile=open('Result of '+filename, 'w')
ctr=0
N=int(inp[ctr])
ctr+=1
#Solving N system of equations.
for x in range(N):
num_var, num_eq=list(map(int, inp[ctr].split()))
ctr+=1
sys_Eq=[]
for y in range(num_eq):
sys_Eq.append(list(map(int, inp[ctr].split())))
ctr+=1
result=equationSolver(sys_Eq, num_eq, num_var)
wfile.write("Solution to Case #"+str(x+1)+": \n")
if result[0]==False:
wfile.write("The given system of equations is inconsistent.\n")
else:
for y in range(num_var):
if result[y+1]=='':
wfile.write('x_'+str(y+1)+ ' is free.\n')
else:
wfile.write('x_'+str(y+1)+' = '+result[y+1]+'\n')
print('Completed Test Case '+str(x+1)+'!!\n')
wfile.close()
|
Python
| 0
|
@@ -4329,16 +4329,21 @@
it will
+read
x_ith is
|
9b5d2929f58a3155edc5f03a3cca14ff25356021
|
Remove pidfile in Container.kill()
|
src/libcask/container.py
|
src/libcask/container.py
|
import os
import os.path
import time
import signal
import subprocess
import libcask.attach
class Container(object):
def __init__(
self,
name,
root_path,
pid_path,
hostname,
ipaddr,
ipaddr_host,
entry_point,
):
# Human-readable name for this container
self.name = name
# Path to the filesystem root directory of the container
self.root_path = root_path
# Path to the pidfile of the container
self.pid_path = pid_path
# Hostname of the container
self.hostname = hostname
# IP Address of the container's virtual ethernet interface
self.ipaddr = ipaddr
# IP Address of the host's end of the virtual ethernet pair
self.ipaddr_host = ipaddr
# Command to run in the new container
self.entry_point = entry_point
def pid(self):
try:
with open(self.pid_path, 'r') as f:
return int(f.read())
except IOError:
return None
def create(self):
os.makedirs(self.root_path)
os.makedirs(os.path.dirname(self.pid_path))
def status(self):
pid = self.pid()
status_path = '/proc/{pid}/status'.format(pid=pid)
try:
with open(status_path, 'r') as f:
return True
except IOError:
return False
def start(self):
entry = self.entry_point.split(' ')
args = ['./cask-clone', self.root_path, self.pid_path] + entry
with open('/dev/null', 'rwb') as devnull:
subprocess.Popen(args, stdin=devnull, stdout=devnull, stderr=devnull)
# TODO - Properly await existence of pidfile. This /sucks/.
time.sleep(1)
print 'pid:', self.pid()
def attach(self):
return libcask.attach.Attachment(self.pid())
def kill(self, sig=None):
os.kill(self.pid(), sig or signal.SIGKILL)
|
Python
| 0.000001
|
@@ -1964,8 +1964,41 @@
IGKILL)%0A
+ os.unlink(self.pid_path)%0A
|
6f61215263cfe02dc50e508514d1d23208e46d92
|
Allow modules context processor works without request.user Fix #524
|
material/frontend/context_processors.py
|
material/frontend/context_processors.py
|
from . import modules as modules_registry
def modules(request):
"""Add current module and modules list to the template context."""
if not hasattr(request, 'user'):
raise ValueError('modules context processor requires "django.contrib.auth.context_processors.auth"'
'to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file.')
module = None
if request.resolver_match:
module = getattr(request.resolver_match.url_name, 'module', None)
return {
'modules': modules_registry.available_modules(request.user),
'current_module': module,
}
|
Python
| 0
|
@@ -134,242 +134,8 @@
%22%22%22%0A
- if not hasattr(request, 'user'):%0A raise ValueError('modules context processor requires %22django.contrib.auth.context_processors.auth%22'%0A 'to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file.')%0A%0A
@@ -148,16 +148,16 @@
= None%0A
+
%0A if
@@ -268,16 +268,16 @@
eturn %7B%0A
-
@@ -335,16 +335,52 @@
st.user)
+ if hasattr(request, 'user') else %5B%5D
,%0A
|
b4a7d177f3d3607244948677c8d33a9dc94ab1a3
|
Revise question docstring
|
lc1093_statistics_from_a_large_sample.py
|
lc1093_statistics_from_a_large_sample.py
|
"""Leetcode 1093. Statistics from a Large Sample
Medium
URL: https://leetcode.com/problems/statistics-from-a-large-sample/
We sampled integers between 0 and 255, and stored the results in an array count:
count[k] is the number of integers we sampled equal to k.
Return the minimum, maximum, mean, median, and mode of the sample respectively,
as an array of floating point numbers. The mode is guaranteed to be unique.
(Recall that the median of a sample is:
The middle element, if the elements of the sample were sorted and the number of
elements is odd;
The average of the middle two elements, if the elements of the sample were
sorted and the number of elements is even.)
Example 1:
Input: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: [1.00000,3.00000,2.37500,2.50000,3.00000]
Example 2:
Input: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: [1.00000,4.00000,2.18182,2.00000,1.00000]
Constraints:
- count.length == 256
- 1 <= sum(count) <= 10^9
- The mode of the sample that count represents is unique.
- Answers within 10^-5 of the true value will be accepted as correct.
"""
class Solution(object):
def sampleStats(self, count):
"""
:type count: List[int]
:rtype: List[float]
"""
pass
def main():
pass
if __name__ == '__main__':
main()
|
Python
| 0.999896
|
@@ -456,17 +456,18 @@
ple is:%0A
-%0A
+-
The midd
@@ -555,16 +555,18 @@
is odd;%0A
+-
The aver
|
0d8c30e58d8b53f90f9318cdf3db26ed1e272602
|
Fix pep8 violation.
|
lms/envs/static.py
|
lms/envs/static.py
|
"""
This config file runs the simplest dev environment using sqlite, and db-based
sessions. Assumes structure:
/envroot/
/db # This is where it'll write the database file
/edx-platform # The location of this repo
/log # Where we're going to write log files
"""
# 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 .common import *
from openedx.core.lib.derived import derive_settings
from openedx.core.lib.logsettings import get_logger_config
STATIC_GRAB = True
LOGGING = get_logger_config(ENV_ROOT / "log",
logging_env="dev",
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ENV_ROOT / "db" / "edx.db",
'ATOMIC_REQUESTS': True,
},
'student_module_history': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ENV_ROOT / "db" / "student_module_history.db",
'ATOMIC_REQUESTS': True,
}
}
CACHES = {
# This is the cache used for most things.
# In staging/prod envs, the sessions also live here.
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'edx_loc_mem_cache',
'KEY_FUNCTION': 'util.memcache.safe_key',
},
# The general cache is what you get if you use our util.cache. It's used for
# things like caching the course.xml file for different A/B test groups.
# We set it to be a DummyCache to force reloading of course.xml in dev.
# In staging environments, we would grab VERSION from data uploaded by the
# push process.
'general': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
'KEY_PREFIX': 'general',
'VERSION': 4,
'KEY_FUNCTION': 'util.memcache.safe_key',
}
}
# Dummy secret key for dev
SECRET_KEY = '85920908f28904ed733fe576320db18cabd7b6cd'
############################ FILE UPLOADS (for discussion forums) #############################
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
MEDIA_ROOT = ENV_ROOT / "uploads"
MEDIA_URL = "/discussion/upfiles/"
FILE_UPLOAD_TEMP_DIR = ENV_ROOT / "uploads"
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
########################## Derive Any Derived Settings #######################
derive_settings(__name__)
|
Python
| 0
|
@@ -715,37 +715,8 @@
dev%22
-,%0A
)%0A%0AD
|
1af17b029cef4c3a197fd3a4813fc704cb277e59
|
use the correct name
|
osmaxx-py/osmaxx/excerptexport/urls.py
|
osmaxx-py/osmaxx/excerptexport/urls.py
|
from django.conf.urls import url
from django.contrib.auth.views import login, logout
from django.views.generic import TemplateView
from osmaxx.excerptexport.views import (
list_downloads,
download_file,
extraction_order_status,
list_orders,
NewExtractionOrderView,
access_denied,
)
except_export_urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="excerptexport/templates/index.html"), name='index'),
url(r'^access_denied/$', access_denied, name='access_denied'),
url(r'^downloads/$', list_downloads, name='downloads'),
url(r'^downloads/(?P<uuid>[A-Za-z0-9_-]+)/$', download_file, name='download'),
url(r'^orders/$', list_orders, name='orders'),
url(r'^orders/new/$', NewExtractionOrderView.as_view(), name='new'),
url(r'^orders/(?P<extraction_order_id>[0-9]+)$', extraction_order_status, name='status')
]
login_logout_patterns = [
url(r'^login/$', login,
{'template_name': 'excerptexport/templates/login.html'}, name='login'),
url(r'^logout/$', logout,
{'template_name': 'excerptexport/templates/logout.html'}, name='logout'),
]
urlpatterns = except_export_urlpatterns + login_logout_patterns
|
Python
| 0.999997
|
@@ -302,24 +302,25 @@
ed,%0A)%0A%0A%0Aexce
+r
pt_export_ur
@@ -1136,16 +1136,17 @@
s = exce
+r
pt_expor
|
dda9b7576269f7dfc7ca864da33f6b047228e667
|
remove armeabi and mips targets
|
config/buildcfg.py
|
config/buildcfg.py
|
import sys, os
import dragon
import apps_tools.android as android
import apps_tools.ios as ios
android_pdraw_dir = os.path.join(dragon.WORKSPACE_DIR,
"packages", "pdraw")
android_jni_dir = os.path.join(android_pdraw_dir,
"libpdraw", "android", "jni")
android_app_dir = os.path.join(android_pdraw_dir,
"apps", "pdraw_android")
#===============================================================================
# Android
#===============================================================================
if dragon.VARIANT == "android":
android_abis = ["armeabi", "armeabi-v7a", "arm64-v8a",
"mips",
"x86"]
android.add_task_build_common(android_abis)
android.add_ndk_build_task(
name="build-jni",
desc="Build native libs & jni",
subtasks=["build-common"],
calldir=android_jni_dir,
module="libpdraw",
abis=android_abis,
extra_args=["PACKAGES_DIR={}".format(os.path.join(dragon.WORKSPACE_DIR,
"packages"))]
)
android.add_ndk_build_task(
name="clean-jni",
desc="Clean native libs & jni",
calldir=android_jni_dir,
module="libpdraw",
abis=android_abis,
extra_args=["PACKAGES_DIR={}".format(os.path.join(dragon.WORKSPACE_DIR,
"packages")),
"clean"],
ignore_failure=True
)
android.add_gradle_task(
name="build-app",
desc="Build the PDrAW Android app in debug",
subtasks=["build-jni"],
calldir=android_app_dir,
target="assembleDebug"
)
android.add_gradle_task(
name="clean-app",
desc="Clean the PDrAW Android app",
subtasks=["clean-jni"],
calldir=android_app_dir,
target="clean"
)
dragon.add_meta_task(
name="build",
desc="Build libs & app",
subtasks=["build-app"]
)
dragon.add_meta_task(
name="clean",
desc="Clean libs & app",
subtasks=["clean-app"]
)
|
Python
| 0
|
@@ -563,19 +563,8 @@
= %5B
-%22armeabi%22,
%22arm
@@ -590,56 +590,8 @@
8a%22,
-%0A %22mips%22,%0A
%22x8
|
b46cf3c17afb7300d7a72725e70650c59a1e67ad
|
Update fun.py
|
code/fun.py
|
code/fun.py
|
import asyncio
import discord
from discord.ext import commands
class Fun:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, no_pm=True)
async def ping(message):
if message.content.startswith('!ping'):
await client.send_message(message.channel, 'Pong!')
|
Python
| 0.000001
|
@@ -129,25 +129,16 @@
%0A
-
@comman
@@ -179,19 +179,16 @@
m=True)%0A
-
async d
@@ -205,21 +205,16 @@
ssage):%0A
-
if
@@ -261,56 +261,48 @@
+
-await client.send_message(message.channel, 'Pong!'
+return await my_bot.say(%22Hello, world!%22
)%0A
+%0A
|
ae3cad82803198d5ec545419e6b078679be50d29
|
Fix bug in scrub output.
|
apps/scrub.py
|
apps/scrub.py
|
"""
Create item database.
"""
import logging
import os
import re
import pydarkstar.logutils
import pydarkstar.scrubbing.ffxiah
import pydarkstar.itemlist
import pydarkstar.options
import pydarkstar.common
class Options(pydarkstar.options.Options):
"""
Reads options from config file, then from command line.
"""
def __init__(self):
super(Options, self).__init__(config='scrub.yaml', description=__doc__)
self.verbose = False # error, info, and debug
self.silent = False # error only
self.stub = 'items' # output file stub
self.overwrite = False # overwrite output
self.backup = False # backup output
self.save = False # save config
self.force = False # redownload
self.pkl = False # save pkl files
self.threads = -1 # cpu threads during download
self.stock01 = 5 # default stock for singles
self.stock12 = 5 # default stock for stacks
self.itemids = [] # a list of item ids
self.urls = [] # a list of category urls
# logging
self.add_argument('--verbose', action='store_true',
help='report debug, info, and error')
self.add_argument('--silent', action='store_true',
help='report error only')
# output
self.add_argument(dest='stub', nargs='?', type=str, default=self.stub,
help='output file stub')
self.add_argument('--overwrite', action='store_true',
help='overwrite output file')
self.add_argument('--backup', action='store_true',
help='backup output file')
self.add_argument('--save', action='store_true',
help='save config file (and exit)')
# scrub parameters
self.add_argument('--force', action='store_true',
help='start from scratch')
self.add_argument('--pkl', action='store_true',
help='save pkl files')
self.add_argument('--threads', type=int, default=self.threads, metavar=self.threads,
help='number of cpu threads to use')
self.add_argument('--urls', type=str, nargs='*', action='append', default=self.urls, metavar='url',
help='a list of category urls')
self.add_argument('--itemids', type=int, nargs='*', action='append', default=self.itemids, metavar='itemids',
help='a list of item ids')
# defaults
self.add_argument('--stock01', type=int, default=self.stock01, metavar=self.stock01,
help='default stock for singles')
self.add_argument('--stock12', type=int, default=self.stock12, metavar=self.stock12,
help='default stock for stacks')
self.exclude('itemids')
self.exclude('urls')
def parse_args(self, args=None):
super(Options, self).parse_args(args)
urls = []
for obj in self.urls:
if isinstance(obj, list):
urls.extend(obj)
else:
urls.append(obj)
self.urls = urls
if not self.urls:
self.urls = None
itemids = []
for obj in self.itemids:
if isinstance(obj, list):
itemids.extend(obj)
else:
itemids.append(obj)
self.itemids = itemids
if not self.itemids:
self.itemids = None
def main():
"""
Main function.
"""
# get options
opts = Options()
opts.parse_args()
pydarkstar.logutils.basicConfig(
verbose=opts.verbose, silent=opts.silent, fname='scrub.log')
logging.info('start')
# log options
opts.log_values(level=logging.INFO)
# save options
if opts.save:
opts.save = False
opts.dump()
return
# check output file name validity
oname = os.path.abspath('{}.csv'.format(re.sub(r'\.csv$', '', opts.stub)))
if not opts.overwrite and not opts.backup:
if os.path.exists(oname):
logging.error('output file already exists!\n\t%s', oname)
logging.error('please use --overwrite or --backup')
exit(-1)
# scub data
scrubber = pydarkstar.scrubbing.ffxiah.FFXIAHScrubber()
scrubber.save = opts.pkl
data = scrubber.scrub(force=opts.force, threads=opts.threads, urls=opts.urls, ids=opts.itemids)
# create item list from data
ilist = pydarkstar.itemlist.ItemList()
for itemid in data:
ilist.add(itemid, pydarkstar.scrubbing.ffxiah.extract(data, itemid, stock01=opts.stock01, stock12=opts.stock12))
# backup file
if opts.backup:
pydarkstar.common.backup(oname, copy=True)
# overwrites if exists, but we checked already
ilist.savecsv(oname)
def cleanup():
logging.info('exit\n')
if __name__ == '__main__':
with pydarkstar.logutils.capture():
main()
cleanup()
|
Python
| 0
|
@@ -4510,25 +4510,16 @@
-ilist.add(itemid,
+kwargs =
pyd
@@ -4608,16 +4608,51 @@
stock12)
+%0A ilist.add(itemid, **kwargs
)%0A%0A #
|
c6b89b10c78c7a053aa7996c9a85cd64c81860c9
|
check whole CSV row
|
apps/views.py
|
apps/views.py
|
from django.http import HttpResponse
from django.views import generic
from django.template import RequestContext, loader
from django.db.utils import ConnectionDoesNotExist
import string, re
from home.models import Crttype, Courts
class OutcomeView(generic.View):
def court_info(self, outcome_data):
court = {}
try:
court['type'] = Crttype.objects.using('outcomes').get(type=outcome_data[5]).name
def get_name(court): return court.name
courts = Courts.objects.using('outcomes').filter(number=outcome_data[11])
if len(courts)==0:
court_names = [outcome_data[11]]
else:
court_names = map(get_name,courts)
court['name'] = court_names
except ConnectionDoesNotExist:
court['type'] = outcome_data[5]
court['name'] = [outcome_data[11]]
finally:
return court
def valid_outcome(self, outcome):
return outcome != '' \
and len(outcome) == 29 \
and re.compile('[0-9.]').match(outcome[0]) \
and re.compile('\d+').match(outcome[1]) \
and re.compile('\d+').match(outcome[2]) \
and re.compile('\d+').match(outcome[3]) \
and re.compile('\d+').match(outcome[4]) \
and re.compile('(MC|CC)').match(outcome[5])
# etc. It's all a bit hardwired, so should be dynamicalised
def get(self, request):
outcome_csv = request.GET.get('csv','')
template = loader.get_template('apps/outcome.html')
outcome_data = string.split(outcome_csv,',')
if self.valid_outcome(outcome_data):
context = RequestContext(request, {
'csv': outcome_csv,
'outcome': {
'court': self.court_info(outcome_data),
'multipers': outcome_data[0],
'amount1': outcome_data[1],
'amount2': outcome_data[2],
'amount3': outcome_data[3],
'amount4': outcome_data[4],
'ofgroup': outcome_data[6],
'force': outcome_data[7],
'age': outcome_data[8],
'month': outcome_data[9],
'year': outcome_data[10],
'sex': outcome_data[12],
'ethcode': outcome_data[13],
'classctn': outcome_data[14],
'plea': outcome_data[15],
'proc': outcome_data[16],
'disp1': outcome_data[17],
'disp2': outcome_data[18],
'disp3': outcome_data[19],
'disp4': outcome_data[20],
'clastype': outcome_data[21],
'priority': outcome_data[22],
'guilty': outcome_data[23],
'sent': outcome_data[24],
'result': outcome_data[25],
'offtyp': outcome_data[26],
'ofclas': outcome_data[27],
'notoff': outcome_data[28],
}
})
else:
context = RequestContext(request, {'csv': outcome_csv, 'outcome': None})
return HttpResponse(template.render(context))
|
Python
| 0
|
@@ -959,16 +959,20 @@
outcome
+_csv
):%0A
@@ -985,478 +985,85 @@
urn
-outcome != '' %5C%0A and len(outcome) == 29 %5C%0A and re.compile('%5B0-9.%5D').match(outcome%5B0%5D) %5C%0A and re.compile('%5Cd+').match(outcome%5B1%5D) %5C%0A and re.compile('%5Cd+').match(outcome%5B2%5D) %5C%0A and re.compile('%5Cd+').match(outcome%5B3%5D) %5C%0A and re.compile('%5Cd+').match(outcome%5B4%5D) %5C%0A and re.compile('(MC%7CCC)').match(outcome%5B5%5D)%0A # etc. It's all a bit hardwired, so should be dynamicalised
+re.compile('(%5Cd+,)%7B5%7D(MC%7CCC),(IND%7CSMO%7CSNM),(%5Cd+,)%7B21%7D%5Cd+').match(outcome_csv)
%0A%0A
@@ -1148,60 +1148,48 @@
-template = loader.get_template('apps/outcome.html')%0A
+if self.valid_outcome(outcome_csv):%0A
@@ -1241,53 +1241,8 @@
,')%0A
- if self.valid_outcome(outcome_data):%0A
@@ -2824,16 +2824,76 @@
None%7D)%0A
+ template = loader.get_template('apps/outcome.html')%0A
|
a307c5fc2555d282dfa6193cdbcfb2d15e185c0c
|
Allow query without table to run
|
aq/parsers.py
|
aq/parsers.py
|
from collections import namedtuple
import collections
from six import string_types
from aq.errors import QueryParsingError
from aq.select_parser import select_stmt, ParseException
TableId = namedtuple('TableId', ('database', 'table', 'alias'))
QueryMetadata = namedtuple('QueryMetadata', ('tables',))
class SelectParser(object):
def __init__(self, options):
self.options = options
@staticmethod
def parse_query(query):
try:
parse_result = select_stmt.parseString(query, parseAll=True)
except ParseException as e:
raise QueryParsingError(e)
if not parse_result.table:
raise QueryParsingError('No table specified in query')
tables = [parse_table_id(tid) for tid in parse_result.table_ids]
parsed_query = concat(parse_result)
return parsed_query, QueryMetadata(tables=tables)
def parse_table_id(table_id):
database = table_id.database[0] if table_id.database else None
table = table_id.table[0] if table_id.table else None
alias = table_id.alias[0] if table_id.alias else None
return TableId(database, table, alias)
def flatten(nested_list):
for item in nested_list:
if isinstance(item, collections.Iterable) and not isinstance(item, string_types):
for nested_item in flatten(item):
yield nested_item
else:
yield item
def concat(tokens):
return ' '.join(flatten(tokens))
|
Python
| 0.000003
|
@@ -1,12 +1,31 @@
+import collections%0A
from collect
@@ -52,28 +52,8 @@
le%0A%0A
-import collections%0A%0A
from
@@ -604,111 +604,8 @@
e)%0A%0A
- if not parse_result.table:%0A raise QueryParsingError('No table specified in query')%0A%0A
|
27cd1984aab447e8c64a8b65cae705c3c55a8922
|
Make conf argument required
|
argus/util.py
|
argus/util.py
|
# Copyright 2014 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 KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import argparse
import base64
import importlib
import logging
import pkgutil
import subprocess
import sys
import six
from argus import config
from argus import remote_client
__all__ = (
'WinRemoteClient',
'decrypt_password',
'run_once',
'get_resource',
'cached_property',
'load_qualified_object',
)
DEFAULT_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
class WinRemoteClient(remote_client.WinRemoteClient):
def run_command_verbose(self, cmd):
"""Run the given command and log anything it returns."""
LOG.info("Running command %s", cmd)
stdout, stderr, exit_code = self.run_remote_cmd(cmd)
LOG.info("The command returned the output %s", stdout)
LOG.info("The stderr of the command was %s", stderr)
LOG.info("The exit code of the command was %s", exit_code)
return stdout
def decrypt_password(private_key, password):
"""Decode password and unencrypts it with private key.
Requires openssl binary available in the path.
"""
unencoded = base64.b64decode(password)
cmd = ['openssl', 'rsautl', '-decrypt', '-inkey', private_key]
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate(unencoded)
proc.stdin.close()
if proc.returncode:
raise Exception("Failed calling openssl with error: {!r}"
.format(err))
return out
# pylint: disable=dangerous-default-value
def run_once(func, state={}, exceptions={}):
"""A memoization decorator, whose purpose is to cache calls."""
@six.wraps(func)
def wrapper(*args, **kwargs):
if func in exceptions:
# Deliberate use of LBYL.
six.reraise(*exceptions[func])
try:
return state[func]
except KeyError:
try:
state[func] = result = func(*args, **kwargs)
return result
except Exception:
exceptions[func] = sys.exc_info()
raise
return wrapper
def trap_failure(func):
"""Call pdb.set_trace when an exception occurs."""
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except BaseException:
# TODO(cpopa): Save the original exception, since pdb will happily
# overwrite it. This makes flake8 scream, though.
# pylint: disable=unused-variable
exc = sys.exc_info() # NOQA
LOG.exception("Exception occurred for func %s", func)
import pdb
pdb.set_trace()
return wrapper
def get_resource(resource):
"""Get the given resource from the list of known resources."""
return pkgutil.get_data('argus.resources', resource)
class cached_property(object): # pylint: disable=invalid-name
"""A property which caches the result on access."""
def __init__(self, func, name=None):
self.func = func
self.name = name or func.__name__
def __get__(self, instance, klass=None):
instance.__dict__[self.name] = result = self.func(instance)
return result
def parse_cli():
"""Parse the command line and return an object with the given options."""
parser = argparse.ArgumentParser()
parser.add_argument('--failfast', action='store_true',
default=False,
help='Fail the tests on the first failure.')
parser.add_argument('--conf', type=str, default=None,
help="Give a path to the argus conf. "
"It should be an .ini file format "
"with a section called [argus].")
parser.add_argument("--git-command", type=str, default=None,
help="Pass a git command which should be interpreted "
"by a recipee.")
parser.add_argument("-p", "--pause", action="store_true",
help="Pause argus before doing any test.")
parser.add_argument("--logging-format",
type=str, default=DEFAULT_FORMAT,
help="The logging format argus should use.")
parser.add_argument("--logging-file",
type=str, default="argus.log",
help="The logging file argus should use.")
parser.add_argument("--test-os-types",
type=str, nargs="*",
help="Test only those scenarios with these OS types. "
"By default, all scenarios are executed. "
"For instance, to run only the Windows and "
"FreeBSD scenarios, use "
"`--test-os-types Windows,FreeBSD`")
parser.add_argument("--test-scenario-type",
type=str,
help="Test only the scenarios with this type. "
"The type can be `smoke` or `deep`. By default, "
"all scenarios types are executed.")
opts = parser.parse_args()
return opts
@run_once
def get_config():
"""Get the argus config object."""
opts = parse_cli()
return config.parse_config(opts.conf)
def get_logger(name="argus", format_string=None):
"""Obtain a new logger object.
The `name` parameter will be the name of the logger
and `format_string` will be the format it will
use for logging.
If it is not given, the the one given at command
line will be used, otherwise the default format.
"""
logger = logging.getLogger(name)
opts = parse_cli()
formatter = logging.Formatter(
format_string or opts.logging_format or DEFAULT_FORMAT)
if not logger.handlers:
# If the logger wasn't obtained another time,
# then it shouldn't have any loggers
if opts.logging_file:
file_handler = logging.FileHandler(opts.logging_file)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
logger.addHandler(stdout_handler)
logger.setLevel(logging.DEBUG)
return logger
def load_qualified_object(obj):
"""Load a qualified object name.
The name must be in the format module:qualname syntax.
"""
mod_name, has_attrs, attrs = obj.partition(":")
obj = module = importlib.import_module(mod_name)
if has_attrs:
parts = attrs.split(".")
obj = module
for part in parts:
obj = getattr(obj, part)
return obj
LOG = get_logger()
|
Python
| 0.002165
|
@@ -4229,35 +4229,36 @@
, type=str,
-default=Non
+required=Tru
e,%0A
|
e1c4bb856f9296db92f2388d1a427204994eb88b
|
version where dependencies have been fixed
|
loompy/_version.py
|
loompy/_version.py
|
__version__ = '1.0.0'
|
Python
| 0
|
@@ -12,11 +12,11 @@
= '1.0.
-0
+1
'%0A
|
e2852dc043f179a8e580447580f66674a3cd1534
|
fix pointer-location delete on codeblock analysis. if we run into a location that's a pointer during code-flow, most times it will not be identified on the location of the instruction, but offset. this also brings up the question: what happens if we completely skip the pointer because it fell within the previous instruction? (most common)
|
vivisect/analysis/generic/codeblocks.py
|
vivisect/analysis/generic/codeblocks.py
|
"""
A function analysis module that will find code blocks in
functions by flow and xrefs. This is basically a mandatory
module which should be snapped in *very* early by parsers.
"""
#FIXME this belongs in the core disassembler loop!
import sys
import envi
import vivisect
from vivisect.const import *
def analyzeFunction(vw, funcva):
blocks = {}
done = {}
todo = [ funcva, ]
brefs = []
size = 0
opcount = 0
while len(todo):
start = todo.pop()
# If we've hit code we've already done, keep going.
if done.get(start):
continue
done[start] = True
blocks[start] = 0
brefs.append( (start, True) )
va = start
# Walk forward through instructions until a branch edge
while True:
loc = vw.getLocation(va)
# If it's not a location, terminate
if loc == None:
blocks[start] = va - start
brefs.append( (va, False) )
break
lva,lsize,ltype,linfo = loc
if ltype == LOC_POINTER:
# pointer analysis mis-identified a pointer,
# so clear and re-analyze instructions.
vw.delLocation(va)
# assume we're add a valid instruction, which is most likely.
vw.makeCode(va)
loc = vw.getLocation(va)
if loc is None:
blocks[start] = va - start
brefs.append( (va, False) )
break
lva,lsize,ltype,linfo = loc
# If it's not an op, terminate
if ltype != LOC_OP:
blocks[start] = va - start
brefs.append( (va, False) )
break
size += lsize
opcount += 1
nextva = va+lsize
# For each of our code xrefs, create a new target.
branch = False
xrefs = vw.getXrefsFrom(va, REF_CODE)
for fromva, tova, rtype, rflags in xrefs:
# We don't handle procedural branches here...
if rflags & envi.BR_PROC:
continue
# For now, we'll skip jmp [import] thunks...
if rflags & envi.BR_DEREF:
continue
branch = True
todo.append(tova )
# If it doesn't fall through, terminate (at nextva)
if linfo & envi.IF_NOFALL:
blocks[start] = nextva - start
brefs.append( (nextva, False) )
break
# If we hit a branch, we are the end of a block...
if branch:
blocks[start] = nextva - start
todo.append( nextva )
break
if vw.getXrefsTo(nextva, REF_CODE):
blocks[start] = nextva - start
todo.append( nextva )
break
va = nextva
# we now have an ordered list of block references!
brefs.sort()
brefs.reverse()
bcnt = 0
while len(brefs):
bva, isbegin = brefs.pop()
if not isbegin:
continue
if len(brefs) == 0:
break
bsize = blocks[bva]
vw.addCodeBlock(bva, bsize, funcva)
bcnt+=1
vw.setFunctionMeta(funcva, 'Size', size)
vw.setFunctionMeta(funcva, 'BlockCount', bcnt)
vw.setFunctionMeta(funcva, "InstructionCount", opcount)
|
Python
| 0.000139
|
@@ -1231,32 +1231,33 @@
vw.delLocation(
+l
va)%0A%0A
@@ -1279,16 +1279,19 @@
e're add
+ing
a valid
|
f48c0b25556c3ea89dcb3bd4c4d9608730689be8
|
Make sure www.example.test is checked.
|
src/test-saml.py
|
src/test-saml.py
|
#!/usr/bin/python3
from sys import argv
from xvfbwrapper import Xvfb
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
print("Admin password " + argv[1])
with Xvfb() as xvfb:
driver = webdriver.Firefox(log_path = "/tmp/geckodriver.log")
driver.get("https://www.example.test/")
title = driver.find_element_by_xpath("//h1/a")
print(title.text)
assert "Not logged in" in title.text
logon_link = driver.find_element_by_xpath("//a[@href][text() = 'login']")
current_url = driver.current_url
logon_link.click()
WebDriverWait(driver, 15).until(expected_conditions.url_changes(current_url))
print(driver.current_url)
logon_form = driver.find_element_by_xpath("//form[input[@name = 'ipsilon_transaction_id']]")
logon_form.find_element_by_id("login_name").send_keys("admin")
logon_form.find_element_by_id("login_password").send_keys(argv[1])
current_url = driver.current_url
logon_form.submit()
WebDriverWait(driver, 15).until(expected_conditions.url_changes(current_url))
print(driver.current_url)
title = driver.find_element_by_xpath("//h1/a")
print(title.text)
assert "Logged in as admin" in title.text
groups = driver.find_element_by_xpath("//tr[td/text() = 'Member of groups']/td[2]")
print(groups.text)
assert "ext:admins" in groups.text
driver.quit()
|
Python
| 0.999101
|
@@ -1053,35 +1053,49 @@
ons.url_
-changes(current_url
+to_be(%22https://www.example.test/%22
))%0A%09prin
|
ad0ef8f6e39b5ebc1e650b3e879d3f7dfea807ac
|
Make one tweak from python-modernize.
|
apitools/base/py/util.py
|
apitools/base/py/util.py
|
#!/usr/bin/env python
"""Assorted utilities shared between parts of apitools."""
import collections
import os
import random
import urllib
import urllib2
import six
from six.moves import http_client
from apitools.base.py import exceptions
__all__ = [
'DetectGae',
'DetectGce',
]
_RESERVED_URI_CHARS = r":/?#[]@!$&'()*+,;="
def DetectGae():
"""Determine whether or not we're running on GAE.
This is based on:
https://developers.google.com/appengine/docs/python/#The_Environment
Returns:
True iff we're running on GAE.
"""
server_software = os.environ.get('SERVER_SOFTWARE', '')
return (server_software.startswith('Development/') or
server_software.startswith('Google App Engine/'))
def DetectGce():
"""Determine whether or not we're running on GCE.
This is based on:
https://cloud.google.com/compute/docs/metadata#runninggce
Returns:
True iff we're running on a GCE instance.
"""
try:
o = urllib2.urlopen('http://metadata.google.internal')
except urllib2.URLError:
return False
return (o.getcode() == http_client.OK and
o.headers.get('metadata-flavor') == 'Google')
def NormalizeScopes(scope_spec):
"""Normalize scope_spec to a set of strings."""
if isinstance(scope_spec, str):
return set(scope_spec.split(' '))
elif isinstance(scope_spec, collections.Iterable):
return set(scope_spec)
raise exceptions.TypecheckError(
'NormalizeScopes expected string or iterable, found %s' % (
type(scope_spec),))
def Typecheck(arg, arg_type, msg=None):
if not isinstance(arg, arg_type):
if msg is None:
if isinstance(arg_type, tuple):
msg = 'Type of arg is "%s", not one of %r' % (type(arg), arg_type)
else:
msg = 'Type of arg is "%s", not "%s"' % (type(arg), arg_type)
raise exceptions.TypecheckError(msg)
return arg
def ExpandRelativePath(method_config, params, relative_path=None):
"""Determine the relative path for request."""
path = relative_path or method_config.relative_path or ''
for param in method_config.path_params:
param_template = '{%s}' % param
# For more details about "reserved word expansion", see:
# http://tools.ietf.org/html/rfc6570#section-3.2.2
reserved_chars = ''
reserved_template = '{+%s}' % param
if reserved_template in path:
reserved_chars = _RESERVED_URI_CHARS
path = path.replace(reserved_template, param_template)
if param_template not in path:
raise exceptions.InvalidUserInputError(
'Missing path parameter %s' % param)
try:
# TODO(craigcitro): Do we want to support some sophisticated
# mapping here?
value = params[param]
except KeyError:
raise exceptions.InvalidUserInputError(
'Request missing required parameter %s' % param)
if value is None:
raise exceptions.InvalidUserInputError(
'Request missing required parameter %s' % param)
try:
if not isinstance(value, six.string_types):
value = str(value)
path = path.replace(param_template,
urllib.quote(value.encode('utf_8'), reserved_chars))
except TypeError as e:
raise exceptions.InvalidUserInputError(
'Error setting required parameter %s to value %s: %s' % (
param, value, e))
return path
def CalculateWaitForRetry(retry_attempt, max_wait=60):
"""Calculates amount of time to wait before a retry attempt.
Wait time grows exponentially with the number of attempts.
A random amount of jitter is added to spread out retry attempts from different
clients.
Args:
retry_attempt: Retry attempt counter.
max_wait: Upper bound for wait time.
Returns:
Amount of time to wait before retrying request.
"""
wait_time = 2 ** retry_attempt
# randrange requires a nonzero interval, so we want to drop it if
# the range is too small for jitter.
if retry_attempt:
max_jitter = (2 ** retry_attempt) / 2
wait_time += random.randrange(-max_jitter, max_jitter)
return min(wait_time, max_wait)
def AcceptableMimeType(accept_patterns, mime_type):
"""Return True iff mime_type is acceptable for one of accept_patterns.
Note that this function assumes that all patterns in accept_patterns
will be simple types of the form "type/subtype", where one or both
of these can be "*". We do not support parameters (i.e. "; q=") in
patterns.
Args:
accept_patterns: list of acceptable MIME types.
mime_type: the mime type we would like to match.
Returns:
Whether or not mime_type matches (at least) one of these patterns.
"""
unsupported_patterns = [p for p in accept_patterns if ';' in p]
if unsupported_patterns:
raise exceptions.GeneratedClientError(
'MIME patterns with parameter unsupported: "%s"' % ', '.join(
unsupported_patterns))
def MimeTypeMatches(pattern, mime_type):
"""Return True iff mime_type is acceptable for pattern."""
# Some systems use a single '*' instead of '*/*'.
if pattern == '*':
pattern = '*/*'
return all(accept in ('*', provided) for accept, provided
in zip(pattern.split('/'), mime_type.split('/')))
return any(MimeTypeMatches(pattern, mime_type) for pattern in accept_patterns)
|
Python
| 0
|
@@ -1262,18 +1262,31 @@
_spec, s
-tr
+ix.string_types
):%0A r
|
dc3a5d1bec7f03efe30c3dcf280301ad9f0eb24c
|
Change derivs function but still need multifield potential to test.
|
pyflation/multifieldmodels.py
|
pyflation/multifieldmodels.py
|
'''multifield.py - Classes for multi field cosmological models
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from scipy import interpolate
import cosmomodels as c
class MultiFieldModels(c.CosmologicalModel):
'''
Parent class for all multifield models.
'''
def __init__(self, *args, **kwargs):
"""Call superclass init method."""
super(MultiFieldModels, self).__init__(*args, **kwargs)
#Set the number of fields using keyword argument, defaults to 1.
self.nfields = kwargs.get("nfields", 1)
#Set field indices. These can be used to select only certain parts of
#the y variable, e.g. y[self.bg_ix] is the array of background values.
self.H_ix = self.nfields*2
self.bg_ix = slice(0,self.nfields*2)
self.pert_ix = slice(self.nfields*2+1, None)
def findH(self, U, y):
"""Return value of Hubble variable, H at y for given potential.
y - array_like: variable array at one time step. So y[1] should be phidot
for the first field and y[n+1] for each subsequent field.
"""
#Get phidots from y, should be second variable for each field.
phidots = y[self.bg_ix][1::2]
#Expression for H
H = np.sqrt(U/(3.0-0.5*(np.sum(phidots**2))))
return H
def potentials(self, y, pot_params=None):
"""Return value of potential at y, along with first and second derivs."""
pass
def findinflend(self):
"""Find the efold time where inflation ends,
i.e. the hubble flow parameter epsilon >1.
Returns tuple of endefold and endindex (in tresult)."""
self.epsilon = self.getepsilon()
if not any(self.epsilon>1):
raise c.ModelError("Inflation did not end during specified number of efoldings. Increase tend and try again!")
endindex = np.where(self.epsilon>=1)[0][0]
#Interpolate results to find more accurate endpoint
tck = interpolate.splrep(self.tresult[:endindex], self.epsilon[:endindex])
t2 = np.linspace(self.tresult[endindex-1], self.tresult[endindex], 100)
y2 = interpolate.splev(t2, tck)
endindex2 = np.where(y2>1)[0][0]
#Return efold of more accurate endpoint
endefold = t2[endindex2]
return endefold, endindex
def getepsilon(self):
"""Return an array of epsilon = -\dot{H}/H values for each timestep."""
#Find Hdot
if len(self.yresult.shape) == 3:
Hdot = np.array(map(self.derivs, self.yresult, self.tresult))[:,self.H_ix,0]
epsilon = - Hdot/self.yresult[:,self.H_ix,0]
else:
Hdot = np.array(map(self.derivs, self.yresult, self.tresult))[:,self.H_ix]
epsilon = - Hdot/self.yresult[:,self.H_ix]
return epsilon
|
Python
| 0
|
@@ -2999,16 +2999,1490 @@
epsilon%0A
+%0Aclass MultiFieldBackground(MultiFieldModels):%0A %22%22%22Basic model with background equations for multiple fields%0A Array of dependent variables y is given by:%0A %0A y%5B0%5D - %5Cphi_a : Background inflaton%0A y%5B1%5D - d%5Cphi_a/d%5Cn : First deriv of %5Cphi_a%0A ...%0A y%5Bself.nfields*2%5D - H: Hubble parameter%0A %22%22%22%0A %0A def __init__(self, *args, **kwargs):%0A %22%22%22Initialize variables and call superclass%22%22%22%0A %0A super(CanonicalBackground, self).__init__(*args, **kwargs)%0A %0A #Set initial H value if None%0A if np.all(self.ystart%5Bself.H_ix%5D == 0.0):%0A U = self.potentials(self.ystart, self.pot_params)%5B0%5D%0A self.ystart%5Bself.H_ix%5D = self.findH(U, self.ystart)%0A %0A def derivs(self, y, t, **kwargs):%0A %22%22%22Basic background equations of motion.%0A dydx%5B0%5D = dy%5B0%5D/dn etc%22%22%22%0A #get potential from function%0A U, dUdphi, d2Udphi2 = self.potentials(y, self.pot_params)%5B0:3%5D %0A %0A #Set derivatives%0A dydx = np.zeros_like(y)%0A %0A bg_indices = arange(0,self.H_ix,2)%0A firstderiv_indices = arange(1,self.H_ix,2)%0A %0A #d%5Cphi_0/dn = y_1%0A dydx%5Bbg_indices%5D = y%5Bfirstderiv_indices%5D %0A %0A #dphi%5Eprime/dn%0A dydx%5Bfirstderiv_indices%5D = -(U*y%5Bfirstderiv_indices%5D + dUdphi)/(y%5Bself.H_ix%5D**2)%0A %0A #dH/dn%0A dydx%5Bself.H_ix%5D = -0.5*(y%5Bfirstderiv_indices%5D**2)*y%5Bself.H_ix%5D%0A%0A return dydx
|
aed103de16687b54c7e66e3adef903d1430e4471
|
remove unused model.
|
ats/models.py
|
ats/models.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
from django.utils.encoding import python_2_unicode_compatible
from . import bigint_patch
class UserExtraAttr(models.Model):
user = models.ForeignKey(User)
expire_dt = models.DateField(null=False)
accounttype = models.IntegerField()
admin.site.register(UserExtraAttr)
@python_2_unicode_compatible
class Project(models.Model):
id = models.AutoField(primary_key=True)
name = models.TextField(blank=False)
start_dt = models.DateField(null=False, blank=False)
end_dt = models.DateField(null=True, blank=True)
sortkey = models.IntegerField(null=False)
def __str__(self):
if self.end_dt:
if self.end_dt < datetime.date.today():
return '%d : %s [closed]' % (self.id, self.name)
else:
return '%d : %s [opened]' % (self.id, self.name)
else:
return '%d : %s [opened]' % (self.id, self.name)
admin.site.register(Project)
@python_2_unicode_compatible
class Job(models.Model):
id = models.AutoField(primary_key=True)
name = models.TextField(blank=False)
sortkey = models.IntegerField(null=False)
invalid = models.BooleanField(default=False)
def __str__(self):
if self.invalid:
return '%d : %s [invalid]' % (self.id, self.name)
else:
return '%d : %s' % (self.id, self.name)
admin.site.register(Job)
@python_2_unicode_compatible
class Task(models.Model):
id = models.AutoField(primary_key=True)
name = models.TextField(blank=False)
job = models.ForeignKey('Job')
sortkey = models.IntegerField(null=False)
invalid = models.BooleanField(default=False)
def __str__(self):
if self.invalid:
return '%d : %s (%s) [invalid]' % (
self.id, self.name, self.job.name)
else:
return '%d : %s (%s)' % (
self.id, self.name, self.job.name)
admin.site.register(Task)
@python_2_unicode_compatible
class ProjectWorker(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User)
project = models.ForeignKey('Project')
job = models.ForeignKey('Job')
invalid = models.BooleanField(default=False)
def __str__(self):
if self.invalid:
return '%d : %s (%s - %s) [invalid]' % (
self.id, self.user.username, self.project.name, self.job.name)
else:
return '%d : %s (%s - %s)' % (
self.id, self.user.username, self.project.name, self.job.name)
admin.site.register(ProjectWorker)
@python_2_unicode_compatible
class UsedTaskTime(models.Model):
id = bigint_patch.BigAutoField(primary_key=True)
user = models.ForeignKey(User)
project = models.ForeignKey('Project')
task = models.ForeignKey('Task')
taskdate = models.DateField(null=False)
tasktime = models.TimeField(null=False)
def __str__(self):
return '%d : [%s - %s] %s - %s - %s' % (
self.id, self.taskdate, self.tasktime,
self.user.username, self.project.name, self.task.name)
admin.site.register(UsedTaskTime)
|
Python
| 0
|
@@ -274,201 +274,8 @@
h%0A%0A%0A
-class UserExtraAttr(models.Model):%0A user = models.ForeignKey(User)%0A expire_dt = models.DateField(null=False)%0A accounttype = models.IntegerField()%0A%0Aadmin.site.register(UserExtraAttr)%0A%0A%0A
@pyt
|
aa9c29dda9522008fefc580abc99ca4ffd369b1e
|
Rework how MPI packing/unpacking is handled.
|
pyfr/backends/cuda/packing.py
|
pyfr/backends/cuda/packing.py
|
# -*- coding: utf-8 -*-
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
from pyfr.backends.cuda.provider import CudaKernelProvider
from pyfr.backends.cuda.queue import CudaComputeKernel, CudaMPIKernel
from pyfr.util import npdtype_to_ctype, npdtype_to_mpitype
class CudaPackingKernels(CudaKernelProvider):
def __init__(self, backend):
pass
def _tplopts(self, view):
return dict(view_order=view.order,
mat_ctype=npdtype_to_ctype(view.viewof.dtype))
def _packunpack(self, op, mpipreqfn, view, pid, tag):
# Get the CUDA pack/unpack kernel
fn = self._get_function('pack', op, 'PPiiiP', self._tplopts(view))
# Determine the MPI data type the view packs to/unpacks from
mpitype = npdtype_to_mpitype(view.viewof.dtype)
# Create a persistent MPI request to send/recv the pack
preq = mpipreqfn((view.hbuf, mpitype), pid, tag)
# Compute the grid and thread-block size
grid, block = self._get_2d_grid_block(fn, view.nrow, view.ncol)
class PackUnpackKernel(CudaComputeKernel):
def __call__(self, stream):
# If we are unpacking then copy the buffer to the GPU
if op == 'unpack':
cuda.memcpy_htod_async(view.gbuf, view.hbuf, stream)
# Call the CUDA kernel (pack or unpack)
fn.prepared_async_call(grid, block, stream, view.viewof.data,
view.data, view.nrow, view.ncol,
view.leaddim, view.gbuf)
# If we have been packing then copy the buffer to the host
if op == 'pack':
cuda.memcpy_dtoh_async(view.hbuf, view.gbuf, stream)
class SendRecvPackKernel(CudaMPIKernel):
def __call__(self, reqlist):
# Start the request and append us to the list of requests
preq.Start()
reqlist.append(preq)
return PackUnpackKernel(), SendRecvPackKernel()
def pack(self, view, mpicomm, pid, tag):
# Delegate; returning (PackUnpackKernel, SendRecvPackKernel)
return self._packunpack('pack', mpicomm.Send_init, view, pid, tag)
def unpack(self, view, mpicomm, pid, tag):
# Delegate; returning (SendRecvPackKernel, PackUnpackKernel)
return self._packunpack('unpack', mpicomm.Recv_init, view, pid,
tag)[::-1]
|
Python
| 0
|
@@ -547,33 +547,12 @@
op,
-mpipreqfn, view, pid, tag
+view
):%0A
@@ -591,16 +591,37 @@
k kernel
+ from the pack module
%0A
@@ -693,256 +693,8 @@
))%0A%0A
- # Determine the MPI data type the view packs to/unpacks from%0A mpitype = npdtype_to_mpitype(view.viewof.dtype)%0A%0A # Create a persistent MPI request to send/recv the pack%0A preq = mpipreqfn((view.hbuf, mpitype), pid, tag)%0A%0A
@@ -1526,32 +1526,367 @@
.gbuf, stream)%0A%0A
+ return PackUnpackKernel()%0A%0A def _sendrecv(self, view, mpipreqfn, pid, tag):%0A # Determine the MPI data type the view packs to/unpacks from%0A mpitype = npdtype_to_mpitype(view.viewof.dtype)%0A%0A # Create a persistent MPI request to send/recv the pack%0A preq = mpipreqfn((view.hbuf, mpitype), pid, tag)%0A%0A
class Se
@@ -2118,28 +2118,8 @@
turn
- PackUnpackKernel(),
Sen
@@ -2164,98 +2164,107 @@
view
-, mpicomm, pid, tag):%0A # Delegate; returning (PackU
+):%0A return self._packu
npack
-Kernel, SendRecvPackKernel)
+('pack', view)%0A%0A def send_pack(self, view, mpicomm, pid, tag):
%0A
@@ -2281,33 +2281,29 @@
n self._
-packunpack('pack'
+sendrecv(view
, mpicom
@@ -2310,30 +2310,24 @@
m.Send_init,
- view,
pid, tag)%0A%0A
@@ -2334,18 +2334,21 @@
def
-un
+recv_
pack(sel
@@ -2388,180 +2388,138 @@
-# Delegate; returning (SendRecvPackKernel, PackUnpackKernel)%0A return self._packunpack('unpack', mpicomm.Recv_init, view, pid,%0A tag)%5B::-1%5D
+return self._sendrecv(view, mpicomm.Recv_init, pid, tag)%0A%0A def unpack(self, view):%0A return self._packunpack('unpack', view)
%0A
|
0bbfcaabcee591ca19702ec071d711ac411597fd
|
Increment version to 0.2.4
|
approvaltests/version.py
|
approvaltests/version.py
|
version_number = "0.2.3"
|
Python
| 0.998885
|
@@ -19,7 +19,7 @@
0.2.
-3
+4
%22%0A
|
1e0947e79e6d65309800fd469a826ae6b72c8ba0
|
Fix scoping error in coverage.
|
pyparser/coverage/__init__.py
|
pyparser/coverage/__init__.py
|
from __future__ import absolute_import, division, print_function, unicode_literals
from .. import source, lexer
import os, codecs
_buf = None
with codecs.open(os.path.join(os.path.dirname(__file__), '..', 'parser.py'),
encoding='utf-8') as f:
_buf = source.Buffer(f.read(), f.name)
# Inject the grammar with locations of rules, because Python's
# builtin tracebacks don't include column numbers.
# This would really be more elegant if it used the parser,
# but the parser doesn't work yet at the time of writing.
def instrument():
rewriter = source.Rewriter(_buf)
lex = lexer.Lexer(_buf, (3, 4))
in_grammar = False
paren_stack = []
stmt_stack = [None]
all_stmt_list = []
in_square = 0
for token in lex:
if token.kind == 'from':
token = lex.next()
if token.kind == '.':
rewriter.replace(token.loc, "..")
if token.kind == 'class':
token = lex.next()
if token.kind == 'ident' and token.value == 'Parser':
in_grammar = True
if not in_grammar:
continue
if token.kind == '.': # skip ast.List
lex.next()
if token.kind == 'ident' and \
token.value in ('action', 'Eps', 'Tok', 'Loc', 'Rule', 'Expect',
'Seq', 'SeqN', 'Alt', 'Opt', 'Star', 'Plus', 'List',
'Newline', 'Oper', 'BinOper', 'BeginEnd'):
lparen = lex.next()
if lparen.kind == '(':
rparen = lex.peek()
if rparen.kind == ')':
lex.next()
rewriter.insert_before(rparen.loc,
"loc=(%d,%d)" % (token.loc.begin_pos, token.loc.end_pos))
else:
paren_stack.append(", loc=(%d,%d)" % (token.loc.begin_pos, token.loc.end_pos))
if token.kind == '(':
paren_stack.append(None)
if token.kind == ')':
data = paren_stack.pop()
if data is not None:
rewriter.insert_before(token.loc, data)
if token.kind == '[':
in_square += 1
elif token.kind == ']':
in_square -= 1
if token.kind in ('def', 'if', 'elif', 'else', 'for') and in_square == 0:
if token.kind == 'def':
ident = lex.next()
if ident.value[0] == '_':
stmt_stack.append(None)
continue
all_stmt_list.append((token.loc.begin_pos, token.loc.end_pos))
stmt_stack.append("_all_stmts[(%d,%d)] = True\n" %
(token.loc.begin_pos, token.loc.end_pos))
elif token.kind == 'lambda':
stmt_stack.append(None)
if token.kind == 'indent':
data = stmt_stack.pop()
if data is not None:
rewriter.insert_after(token.loc, data + " " * token.loc.column())
with codecs.open(os.path.join(os.path.dirname(__file__), 'parser.py'), 'w',
encoding='utf-8') as f:
f.write(rewriter.rewrite().source)
f.write("\n_all_stmts = {%s}\n" % ', '.join(["(%d,%d): False" % x for x in all_stmt_list]))
# Produce an HTML report for test coverage of parser rules.
def report(parser, name='parser'):
all_locs = dict()
for rule in parser._all_rules:
pts = len(rule.covered)
covered = len(list(filter(lambda x: x, rule.covered)))
if rule.loc in all_locs:
pts_, covered_ = all_locs[rule.loc]
if covered > covered_:
all_locs[rule.loc] = pts, covered
else:
all_locs[rule.loc] = pts, covered
rewriter = source.Rewriter(_buf)
total_pts = 0
total_covered = 0
for loc in all_locs:
pts, covered = all_locs[loc]
if covered == 0:
klass, hint = 'uncovered', None
elif covered < pts:
klass, hint = 'partial', ', '.join(map(lambda x: "yes" if x else "no", rule.covered))
else:
klass, hint = 'covered', None
sloc = source.Range(_buf, *rule.loc)
if hint:
rewriter.insert_before(sloc, r"<span class='%s' title='%s'>" % (klass, hint))
else:
rewriter.insert_before(sloc, r"<span class='%s'>" % klass)
rewriter.insert_after(sloc, r"</span>")
total_pts += pts
total_covered += covered
for stmt in parser._all_stmts:
loc = source.Range(_buf, *stmt)
if parser._all_stmts[stmt]:
rewriter.insert_before(loc, r"<span class='covered'>")
else:
rewriter.insert_before(loc, r"<span class='uncovered'>")
rewriter.insert_after(loc, r"</span>")
total_pts += 1
total_covered += (1 if parser._all_stmts[stmt] else 0)
print("GRAMMAR COVERAGE: %.2f%%" % (total_covered / total_pts * 100))
content = rewriter.rewrite().source
content = '\n'.join(map(
lambda x: r"<span id='{0}' class='line'>{1}</span>".format(*x),
enumerate(content.split("\n"), 1)))
with codecs.open(os.path.join(os.path.dirname(__file__), '..', '..',
'doc', 'coverage', name + '.html'), 'w', encoding='utf-8') as f:
f.write(r"""
<!DOCTYPE html>
<html>
<head>
<title>{percentage:.2f}%: {file} coverage report</title>
<style type="text/css">
.uncovered {{ background-color: #FFCAAD; }}
.partial {{
background-color: #FFFFB4;
border-bottom: 1px dotted black;
}}
.covered {{ background-color: #9CE4B7; }}
pre {{ counter-reset: line; }}
.line::before {{
display: inline-block;
width: 4ex;
padding-right: 1em;
text-align: right;
color: gray;
content: counter(line);
counter-increment: line;
}}
</style>
</head>
<body>
<h1>{percentage:.2f}% ({covered}/{pts}): {file} coverage report</h1>
<pre>{content}</pre>
</body>
</html>
""".format(percentage=total_covered / total_pts * 100,
pts=total_pts, covered=total_covered,
file=os.path.basename(_buf.name),
content=content))
# Create the instrumented parser when `import pyparser.coverage.parser`
# is invoked. Not intended for any use except running the internal testsuite.
instrument()
|
Python
| 0
|
@@ -4149,21 +4149,16 @@
(_buf, *
-rule.
loc)%0A
|
1eda7cfbda31ab7b39182e4a2fdacf8bfcf147a2
|
Update __init__.py
|
pytorch_lightning/__init__.py
|
pytorch_lightning/__init__.py
|
"""Root package info."""
__version__ = '0.9.1rc4'
__author__ = 'William Falcon et al.'
__author_email__ = 'waf2107@columbia.edu'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright (c) 2018-2020, %s.' % __author__
__homepage__ = 'https://github.com/PyTorchLightning/pytorch-lightning'
# this has to be simple string, see: https://github.com/pypa/twine/issues/522
__docs__ = (
"PyTorch Lightning is the lightweight PyTorch wrapper for ML researchers."
" Scale your models. Write less boilerplate."
)
__long_docs__ = """
Lightning is a way to organize your PyTorch code to decouple the science code from the engineering.
It's more of a style-guide than a framework.
In Lightning, you organize your code into 3 distinct categories:
1. Research code (goes in the LightningModule).
2. Engineering code (you delete, and is handled by the Trainer).
3. Non-essential research code (logging, etc. this goes in Callbacks).
Although your research/production project might start simple, once you add things like GPU AND TPU training,
16-bit precision, etc, you end up spending more time engineering than researching.
Lightning automates AND rigorously tests those parts for you.
Overall, Lightning guarantees rigorously tested, correct, modern best practices for the automated parts.
Documentation
-------------
- https://pytorch-lightning.readthedocs.io/en/latest
- https://pytorch-lightning.readthedocs.io/en/stable
"""
import logging as python_logging
_logger = python_logging.getLogger("lightning")
_logger.addHandler(python_logging.StreamHandler())
_logger.setLevel(python_logging.INFO)
try:
# This variable is injected in the __builtins__ by the build
# process. It used to enable importing subpackages of skimage when
# the binaries are not built
__LIGHTNING_SETUP__
except NameError:
__LIGHTNING_SETUP__ = False
if __LIGHTNING_SETUP__:
import sys # pragma: no-cover
sys.stdout.write(f'Partial import of `{__name__}` during the build process.\n') # pragma: no-cover
# We are not importing the rest of the lightning during the build process, as it may not be compiled yet
else:
from pytorch_lightning.core import LightningDataModule, LightningModule
from pytorch_lightning.core.step_result import TrainResult, EvalResult
from pytorch_lightning.callbacks import Callback
from pytorch_lightning.trainer import Trainer
from pytorch_lightning.utilities.seed import seed_everything
from pytorch_lightning import metrics
__all__ = [
'Trainer',
'LightningDataModule',
'LightningModule',
'Callback',
'seed_everything',
'metrics',
'EvalResult',
'TrainResult',
]
# necessary for regular bolts imports. Skip exception since bolts is not always installed
try:
from pytorch_lightning import bolts
except ImportError:
pass
# __call__ = __all__
# for compatibility with namespace packages
__import__('pkg_resources').declare_namespace(__name__)
|
Python
| 0.000072
|
@@ -40,14 +40,15 @@
'0.
-9.1rc4
+10.0rc1
'%0A__
|
d24cf56d0ad2e8388eb931b10c170df86870c5b0
|
Update __init__.py (#4308)
|
pytorch_lightning/__init__.py
|
pytorch_lightning/__init__.py
|
"""Root package info."""
__version__ = '1.0.3'
__author__ = 'William Falcon et al.'
__author_email__ = 'waf2107@columbia.edu'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright (c) 2018-2020, %s.' % __author__
__homepage__ = 'https://github.com/PyTorchLightning/pytorch-lightning'
# this has to be simple string, see: https://github.com/pypa/twine/issues/522
__docs__ = (
"PyTorch Lightning is the lightweight PyTorch wrapper for ML researchers."
" Scale your models. Write less boilerplate."
)
__long_docs__ = """
Lightning is a way to organize your PyTorch code to decouple the science code from the engineering.
It's more of a style-guide than a framework.
In Lightning, you organize your code into 3 distinct categories:
1. Research code (goes in the LightningModule).
2. Engineering code (you delete, and is handled by the Trainer).
3. Non-essential research code (logging, etc. this goes in Callbacks).
Although your research/production project might start simple, once you add things like GPU AND TPU training,
16-bit precision, etc, you end up spending more time engineering than researching.
Lightning automates AND rigorously tests those parts for you.
Overall, Lightning guarantees rigorously tested, correct, modern best practices for the automated parts.
Documentation
-------------
- https://pytorch-lightning.readthedocs.io/en/latest
- https://pytorch-lightning.readthedocs.io/en/stable
"""
import logging as python_logging
_logger = python_logging.getLogger("lightning")
_logger.addHandler(python_logging.StreamHandler())
_logger.setLevel(python_logging.INFO)
try:
# This variable is injected in the __builtins__ by the build
# process. It used to enable importing subpackages of skimage when
# the binaries are not built
__LIGHTNING_SETUP__
except NameError:
__LIGHTNING_SETUP__ = False
if __LIGHTNING_SETUP__:
import sys # pragma: no-cover
sys.stdout.write(f'Partial import of `{__name__}` during the build process.\n') # pragma: no-cover
# We are not importing the rest of the lightning during the build process, as it may not be compiled yet
else:
from pytorch_lightning.core import LightningDataModule, LightningModule
from pytorch_lightning.callbacks import Callback
from pytorch_lightning.trainer import Trainer
from pytorch_lightning.utilities.seed import seed_everything
from pytorch_lightning import metrics
__all__ = [
'Trainer',
'LightningDataModule',
'LightningModule',
'Callback',
'seed_everything',
'metrics',
]
# necessary for regular bolts imports. Skip exception since bolts is not always installed
try:
from pytorch_lightning import bolts
except ImportError:
pass
# __call__ = __all__
# for compatibility with namespace packages
__import__('pkg_resources').declare_namespace(__name__)
|
Python
| 0
|
@@ -38,17 +38,20 @@
= '1.0.
-3
+4rc0
'%0A__auth
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.