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
|
---|---|---|---|---|---|---|---|
0abb8f6d266408f20c751726460ae2d87f307583
|
solve 1 problem
|
solutions/factorial-trailing-zeroes.py
|
solutions/factorial-trailing-zeroes.py
|
Python
| 0.000027 |
@@ -0,0 +1,667 @@
+#!/usr/bin/env python%0A# encoding: utf-8%0A%0A%22%22%22%0Afactorial-trailing-zeroes.py%0A %0ACreated by Shuailong on 2016-02-21.%0A%0Ahttps://leetcode.com/problems/factorial-trailing-zeroes/.%0A%0A%22%22%22%0A%0Aclass Solution(object):%0A def trailingZeroes(self, n):%0A %22%22%22%0A :type n: int%0A :rtype: int%0A %22%22%22%0A count = 0%0A max_iter = 15 # 5**14 %3E max_int%0A for fact in range(1, max_iter):%0A count += n / 5 ** fact%0A%0A return count%0A %0A %0A%0A%0Adef main():%0A solution = Solution()%0A n = 25%0A for n in range(1, 100):%0A print solution.trailingZeroes2(n), solution.trailingZeroes(n)%0A%0A %0Aif __name__ == '__main__':%0A main()%0A%0A
|
|
c8fa91104d712bf2743b07b5edd5f38a040d6507
|
Add unit tests for invoke_post_run
|
st2common/tests/unit/test_runners_utils.py
|
st2common/tests/unit/test_runners_utils.py
|
Python
| 0 |
@@ -0,0 +1,2762 @@
+# Licensed to the StackStorm, Inc ('StackStorm') under one or more%0A# contributor license agreements. See the NOTICE file distributed with%0A# this work for additional information regarding copyright ownership.%0A# The ASF licenses this file to You under the Apache License, Version 2.0%0A# (the %22License%22); you may not use this file except in compliance with%0A# the License. You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Aimport mock%0A%0Afrom st2common.runners import utils%0Afrom st2common.services import executions as exe_svc%0Afrom st2common.util import action_db as action_db_utils%0Afrom st2tests import base%0Afrom st2tests import fixturesloader%0A%0A%0Afrom st2tests import config as tests_config%0Atests_config.parse_args()%0A%0A%0AFIXTURES_PACK = 'generic'%0A%0ATEST_FIXTURES = %7B%0A 'liveactions': %5B'liveaction1.yaml'%5D,%0A 'actions': %5B'local.yaml'%5D,%0A 'executions': %5B'execution1.yaml'%5D,%0A 'runners': %5B'run-local.yaml'%5D%0A%7D%0A%0A%0Aclass RunnersUtilityTests(base.CleanDbTestCase):%0A def __init__(self, *args, **kwargs):%0A super(RunnersUtilityTests, self).__init__(*args, **kwargs)%0A self.models = None%0A%0A def setUp(self):%0A super(RunnersUtilityTests, self).setUp()%0A%0A loader = fixturesloader.FixturesLoader()%0A%0A self.models = loader.save_fixtures_to_db(%0A fixtures_pack=FIXTURES_PACK,%0A fixtures_dict=TEST_FIXTURES%0A )%0A%0A self.liveaction_db = self.models%5B'liveactions'%5D%5B'liveaction1.yaml'%5D%0A exe_svc.create_execution_object(self.liveaction_db)%0A self.action_db = action_db_utils.get_action_by_ref(self.liveaction_db.action)%0A%0A @mock.patch.object(action_db_utils, 'get_action_by_ref', mock.MagicMock(return_value=None))%0A def test_invoke_post_run_action_provided(self):%0A utils.invoke_post_run(self.liveaction_db, action_db=self.action_db)%0A action_db_utils.get_action_by_ref.assert_not_called()%0A%0A def test_invoke_post_run_action_exists(self):%0A utils.invoke_post_run(self.liveaction_db)%0A%0A @mock.patch.object(action_db_utils, 'get_action_by_ref', mock.MagicMock(return_value=None))%0A @mock.patch.object(action_db_utils, 'get_runnertype_by_name', mock.MagicMock(return_value=None))%0A def test_invoke_post_run_action_does_not_exist(self):%0A utils.invoke_post_run(self.liveaction_db)%0A action_db_utils.get_action_by_ref.assert_called_once()%0A action_db_utils.get_runnertype_by_name.assert_not_called()%0A
|
|
8977f320979998c9f18cfa7629c1811c7082dddf
|
Add setup.py (sigh)
|
setup.py
|
setup.py
|
Python
| 0 |
@@ -0,0 +1,700 @@
+import setuptools%0A%0Awith open(%22README.md%22, %22r%22) as fh:%0A long_description = fh.read()%0A%0Asetuptools.setup(%0A name=%22webxpath%22, # Replace with your own username%0A version=%220.0.2%22,%0A author=%22Shiplu Mokaddim%22,%0A author_email=%[email protected]%22,%0A description=%22Run XPath query and expressions against websites%22,%0A long_description=long_description,%0A long_description_content_type=%22text/markdown%22,%0A url=%22https://github.com/shiplu/webxpath%22,%0A packages=setuptools.find_packages(),%0A classifiers=%5B%0A %22Programming Language :: Python :: 3%22,%0A %22License :: OSI Approved :: Apache License 2.0%22,%0A %22Operating System :: OS Independent%22,%0A %5D,%0A python_requires=%22%3E=3.6%22,%0A)%0A
|
|
9af2c53af417295842f8ae329a8bb8abc99f693d
|
add setup.py file
|
setup.py
|
setup.py
|
Python
| 0.000001 |
@@ -0,0 +1,165 @@
+#!/usr/bin/env python%0Afrom distutils.core import setup%0A%0Asetup(%0A name = 's7n-blog',%0A version = %221a1%22,%0A packages = %5B's7n', 's7n.blog'%5D,%0A )%0A
|
|
1695dd95ee7750e355ac64d527ff75fb5ecbbdc7
|
Remove unnecessary reparameterization_type specification for tf.distributions.Exponential.
|
tensorflow/python/ops/distributions/exponential.py
|
tensorflow/python/ops/distributions/exponential.py
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""The Exponential distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import random_ops
from tensorflow.python.ops.distributions import gamma
from tensorflow.python.util.tf_export import tf_export
__all__ = [
"Exponential",
"ExponentialWithSoftplusRate",
]
@tf_export("distributions.Exponential")
class Exponential(gamma.Gamma):
"""Exponential distribution.
The Exponential distribution is parameterized by an event `rate` parameter.
#### Mathematical Details
The probability density function (pdf) is,
```none
pdf(x; lambda, x > 0) = exp(-lambda x) / Z
Z = 1 / lambda
```
where `rate = lambda` and `Z` is the normalizaing constant.
The Exponential distribution is a special case of the Gamma distribution,
i.e.,
```python
Exponential(rate) = Gamma(concentration=1., rate)
```
The Exponential distribution uses a `rate` parameter, or "inverse scale",
which can be intuited as,
```none
X ~ Exponential(rate=1)
Y = X / rate
```
"""
def __init__(self,
rate,
validate_args=False,
allow_nan_stats=True,
name="Exponential"):
"""Construct Exponential distribution with parameter `rate`.
Args:
rate: Floating point tensor, equivalent to `1 / mean`. Must contain only
positive values.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`, statistics
(e.g., mean, mode, variance) use the value "`NaN`" to indicate the
result is undefined. When `False`, an exception is raised if one or
more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.
"""
parameters = dict(locals())
# Even though all statistics of are defined for valid inputs, this is not
# true in the parent class "Gamma." Therefore, passing
# allow_nan_stats=True
# through to the parent class results in unnecessary asserts.
with ops.name_scope(name, values=[rate]) as name:
self._rate = ops.convert_to_tensor(rate, name="rate")
super(Exponential, self).__init__(
concentration=array_ops.ones([], dtype=self._rate.dtype),
rate=self._rate,
allow_nan_stats=allow_nan_stats,
validate_args=validate_args,
name=name)
# While the Gamma distribution is not reparameterizable, the exponential
# distribution is.
self._reparameterization_type = True
self._parameters = parameters
self._graph_parents += [self._rate]
@staticmethod
def _param_shapes(sample_shape):
return {"rate": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)}
@property
def rate(self):
return self._rate
def _sample_n(self, n, seed=None):
shape = array_ops.concat([[n], array_ops.shape(self._rate)], 0)
# Uniform variates must be sampled from the open-interval `(0, 1)` rather
# than `[0, 1)`. To do so, we use `np.finfo(self.dtype.as_numpy_dtype).tiny`
# because it is the smallest, positive, "normal" number. A "normal" number
# is such that the mantissa has an implicit leading 1. Normal, positive
# numbers x, y have the reasonable property that, `x + y >= max(x, y)`. In
# this case, a subnormal number (i.e., np.nextafter) can cause us to sample
# 0.
sampled = random_ops.random_uniform(
shape,
minval=np.finfo(self.dtype.as_numpy_dtype).tiny,
maxval=1.,
seed=seed,
dtype=self.dtype)
return -math_ops.log(sampled) / self._rate
class ExponentialWithSoftplusRate(Exponential):
"""Exponential with softplus transform on `rate`."""
def __init__(self,
rate,
validate_args=False,
allow_nan_stats=True,
name="ExponentialWithSoftplusRate"):
parameters = dict(locals())
with ops.name_scope(name, values=[rate]) as name:
super(ExponentialWithSoftplusRate, self).__init__(
rate=nn.softplus(rate, name="softplus_rate"),
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
name=name)
self._parameters = parameters
|
Python
| 0.000016 |
@@ -3581,149 +3581,8 @@
me)%0A
- # While the Gamma distribution is not reparameterizable, the exponential%0A # distribution is.%0A self._reparameterization_type = True%0A
|
e1be390ab7a90d1efdb75a0b2e04c6414645a23c
|
Create setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001 |
@@ -0,0 +1,1643 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A%0Atry:%0A from setuptools import setup%0Aexcept ImportError:%0A from distutils.core import setup%0A%0A%0Awith open('README.rst') as readme_file:%0A readme = readme_file.read()%0A%0Awith open('HISTORY.rst') as history_file:%0A history = history_file.read().replace('.. :changelog:', '')%0A%0Arequirements = %5B%0A # TODO: put package requirements here%0A%5D%0A%0Asetup(%0A name='pdsspect',%0A version='0.1.0',%0A description=%22PDS Image Viewer%22,%0A long_description=readme + '%5Cn%5Cn' + history,%0A author=%22PlanetaryPy Developers%22,%0A author_email='[email protected]',%0A url='https://github.com/planetarypy/pdsspect',%0A packages=%5B%0A 'pdsspect',%0A %5D,%0A package_dir=%7B'pdsspect':%0A 'pdsspect'%7D,%0A include_package_data=True,%0A install_requires=%5B%0A 'ginga==2.6.0',%0A 'planetaryimage%3E=0.5.0',%0A 'matplotlib%3E=1.5.1',%0A 'QtPy%3E=1.2.1'%0A %5D,%0A license=%22BSD%22,%0A zip_safe=False,%0A keywords='pdsspect',%0A classifiers=%5B%0A 'Development Status :: 2 - Pre-Alpha',%0A 'Intended Audience :: Developers',%0A 'License :: OSI Approved :: BSD License',%0A 'Natural Language :: English',%0A %22Programming Language :: Python :: 2%22,%0A 'Programming Language :: Python :: 2.6',%0A 'Programming Language :: Python :: 2.7',%0A 'Programming Language :: Python :: 3',%0A 'Programming Language :: Python :: 3.3',%0A 'Programming Language :: Python :: 3.4',%0A 'Programming Language :: Python :: 3.5',%0A %5D,%0A entry_points=%7B%0A 'console_scripts': %5B%0A 'pdsspect = pdsspect.pdsspect:cli'%0A %5D,%0A %7D%0A)%0A
|
|
a4b9e5849fdff1875a36116c1c6948c1621990fe
|
rename gcp -> gcloud
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages, Command
from setuptools.command.test import test as TestCommand
import os
import sys
# Kept manually in sync with airflow.__version__
version = '1.6.2'
class Tox(TestCommand):
user_options = [('tox-args=', None, "Arguments to pass to tox")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.tox_args = ''
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import tox
errno = tox.cmdline(args=self.tox_args.split())
sys.exit(errno)
class CleanCommand(Command):
"""Custom clean command to tidy up the project root."""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
os.system('rm -vrf ./build ./dist ./*.pyc ./*.tgz ./*.egg-info')
async = [
'greenlet>=0.4.9',
'eventlet>= 0.9.7',
'gevent>=0.13'
]
celery = [
'celery>=3.1.17',
'flower>=0.7.3'
]
crypto = ['cryptography>=0.9.3']
doc = [
'sphinx>=1.2.3',
'sphinx-argparse>=0.1.13',
'sphinx-rtd-theme>=0.1.6',
'Sphinx-PyPI-upload>=0.2.1'
]
docker = ['docker-py>=1.6.0']
druid = ['pydruid>=0.2.1']
gcp = [
'gcloud>=1.1.0',
]
gcp_api = [
'oauth2client>=1.5.2, <2.0.0',
'httplib2',
]
hdfs = ['snakebite>=2.4.13']
webhdfs = ['hdfs[dataframe,avro,kerberos]>=2.0.4']
hive = [
'hive-thrift-py>=0.0.1',
'pyhive>=0.1.3',
'pyhs2>=0.6.0',
]
jdbc = ['jaydebeapi>=0.2.0']
mssql = ['pymssql>=2.1.1', 'unicodecsv>=0.13.0']
mysql = ['mysqlclient>=1.3.6']
optional = ['librabbitmq>=1.6.1']
oracle = ['cx_Oracle>=5.1.2']
postgres = ['psycopg2>=2.6']
s3 = [
'boto>=2.36.0',
'filechunkio>=1.6',
]
samba = ['pysmbclient>=0.1.3']
slack = ['slackclient>=0.15']
statsd = ['statsd>=3.0.1, <4.0']
vertica = ['vertica-python>=0.5.1']
ldap = ['ldap3>=0.9.9.1']
kerberos = ['pykerberos>=1.1.8']
password = [
'bcrypt>=2.0.0',
'flask-bcrypt>=0.7.1',
]
github_enterprise = ['Flask-OAuthlib>=0.9.1']
qds = ['qds-sdk>=1.9.0']
all_dbs = postgres + mysql + hive + mssql + hdfs + vertica
devel = ['lxml>=3.3.4', 'nose', 'mock']
devel += all_dbs + doc + samba + s3 + slack + crypto + oracle + docker
setup(
name='airflow',
description='Programmatically author, schedule and monitor data pipelines',
version=version,
packages=find_packages(),
package_data={'': ['airflow/alembic.ini']},
include_package_data=True,
zip_safe=False,
scripts=['airflow/bin/airflow'],
install_requires=[
'alembic>=0.8.3, <0.9',
'babel>=1.3, <2.0',
'chartkick>=0.4.2, < 0.5',
'croniter>=0.3.8, <0.4',
'dill>=0.2.2, <0.3',
'flask>=0.10.1, <0.11',
'flask-admin>=1.4.0, <2.0.0',
'flask-cache>=0.13.1, <0.14',
'flask-login==0.2.11',
'future>=0.15.0, <0.16',
'gunicorn>=19.3.0, <19.4.0', # 19.4.? seemed to have issues
'jinja2>=2.7.3, <3.0',
'markdown>=2.5.2, <3.0',
'pandas>=0.15.2, <1.0.0',
'pygments>=2.0.1, <3.0',
'python-dateutil>=2.3, <3',
'requests>=2.5.1, <3',
'setproctitle>=1.1.8, <2',
'sqlalchemy>=0.9.8',
'thrift>=0.9.2, <0.10',
'Flask-WTF==0.12'
],
extras_require={
'all': devel + optional,
'all_dbs': all_dbs,
'async': async,
'celery': celery,
'crypto': crypto,
'devel': devel,
'doc': doc,
'docker': docker,
'druid': druid,
'gcp': gcp,
'gcp_api': gcp_api,
'hdfs': hdfs,
'hive': hive,
'jdbc': jdbc,
'mssql': mssql,
'mysql': mysql,
'oracle': oracle,
'postgres': postgres,
's3': s3,
'samba': samba,
'slack': slack,
'statsd': statsd,
'vertica': vertica,
'ldap': ldap,
'webhdfs': webhdfs,
'kerberos': kerberos,
'password': password,
'github_enterprise': github_enterprise,
'qds': qds
},
author='Maxime Beauchemin',
author_email='[email protected]',
url='https://github.com/airbnb/airflow',
download_url=(
'https://github.com/airbnb/airflow/tarball/' + version),
cmdclass={'test': Tox,
'extra_clean': CleanCommand,
},
)
|
Python
| 0.000003 |
@@ -1359,17 +1359,20 @@
2.1'%5D%0Agc
-p
+loud
= %5B%0A
@@ -3676,15 +3676,21 @@
'gc
-p
+loud
': gc
-p
+loud
,%0A
|
18c0682306ee383d0eaad467d8fd7c9f74bb6e4f
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001 |
@@ -0,0 +1,333 @@
+#!/usr/bin/env python%0A# encoding: utf-8%0A%0Afrom setuptools import setup # , find_packages%0A%0Asetup(%0A name='pyoptwrapper',%0A version='1.0',%0A description='wrapper to pyopt',%0A author='Andrew Ning',%0A author_email='[email protected]',%0A py_modules=%5B'pyoptwrapper'%5D,%0A license='Apache License, Version 2.0',%0A zip_safe=False%0A)
|
|
a03fa3d725f296d3fa3fda323171924671ec65c0
|
add setup.py for setuptools support
|
setup.py
|
setup.py
|
Python
| 0 |
@@ -0,0 +1,554 @@
+from setuptools import setup, find_packages%0A%0Asetup(%0A name='mtools', %0A version='1.0.0',%0A packages=find_packages(),%0A scripts=%5B'scripts/mlaunch','scripts/mlog2json','scripts/mlogdistinct',%0A 'scripts/mlogfilter','scripts/mlogmerge','scripts/mlogversion',%0A 'scripts/mlogvis','scripts/mplotqueries'%5D,%0A include_package_data=True,%0A author='Thomas Rueckstiess',%0A author_email='[email protected]',%0A url='https://github.com/rueckstiess/mtools',%0A description='Useful scripts to parse and visualize MongoDB log files.',%0A)
|
|
b106d4fdaf1667061879dd170ddeec1bde2042aa
|
Add setup.py.
|
setup.py
|
setup.py
|
Python
| 0 |
@@ -0,0 +1,325 @@
+from distutils.core import setup%0A%0Asetup(name='twittytwister',%0A version='0.1',%0A description='Twitter client for Twisted Python',%0A author='Dustin Sallings',%0A author_email='[email protected]',%0A url='http://github.com/dustin/twitty-twister/',%0A license='MIT',%0A platforms='any',%0A packages=%5B'twittytwister'%5D,%0A)%0A
|
|
3ab1c4c28f816d0c6495ce5d7b14b854ec77f754
|
Setting version number to 0.2.0
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
class UltraMagicString(object):
'''
Taken from
http://stackoverflow.com/questions/1162338/whats-the-right-way-to-use-unicode-metadata-in-setup-py
'''
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
def __unicode__(self):
return self.value.decode('UTF-8')
def __add__(self, other):
return UltraMagicString(self.value + str(other))
def split(self, *args, **kw):
return self.value.split(*args, **kw)
long_description = UltraMagicString(file('README').read())
setup(
name = 'django-autofixture',
version = '0.2.0pre1',
url = 'https://launchpad.net/django-autofixture',
license = 'BSD',
description = 'Provides tools to auto generate test data.',
long_description = long_description,
author = UltraMagicString('Gregor Müllegger'),
author_email = '[email protected]',
packages = find_packages('src'),
package_dir = {'': 'src'},
include_package_data = True,
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
zip_safe = False,
install_requires = ['setuptools'],
)
|
Python
| 0.999493 |
@@ -723,12 +723,8 @@
.2.0
-pre1
',%0A
|
8ee80a5e346d5b952f3abacc21878da14c13c9f5
|
Make app an owner of file formats.
|
setup.py
|
setup.py
|
# coding=utf-8
import sys
import os
if sys.platform.startswith('darwin'):
from setuptools import setup
APP = ['Cura/cura.py']
DATA_FILES = ['Cura/LICENSE', 'Cura/resources/images', 'Cura/resources/meshes', 'Cura/resources/example/', 'Cura/resources/firmware/']
PLIST = {
u'CFBundleName': u'Cura',
u'CFBundleShortVersionString': u'12.11',
u'CFBundleVersion': u'12.11',
u'CFBundleIdentifier': u'com.ultimaker.Cura',
u'LSMinimumSystemVersion': u'10.6',
u'LSApplicationCategoryType': u'public.app-category.graphics-design',
u'CFBundleDocumentTypes': [
{
u'CFBundleTypeRole': u'Viewer',
u'LSItemContentTypes': [u'com.pleasantsoftware.uti.stl'],
u'LSHandlerRank': u'Alternate',
},
{
u'CFBundleTypeRole': u'Viewer',
u'LSItemContentTypes': [u'org.khronos.collada.digital-asset-exchange'],
u'LSHandlerRank': u'Alternate'
},
{
u'CFBundleTypeName': u'Wavefront 3D Object',
u'CFBundleTypeExtensions': [u'obj'],
u'CFBundleTypeMIMETypes': [u'application/obj-3d'],
u'CFBundleTypeRole': u'Viewer',
u'LSHandlerRank': u'Alternate'
}
],
u'UTImportedTypeDeclarations': [
{
u'UTTypeIdentifier': u'com.pleasantsoftware.uti.stl',
u'UTTypeConformsTo': [u'public.data'],
u'UTTypeDescription': u'Stereo Lithography 3D object',
u'UTTypeReferenceURL': u'http://en.wikipedia.org/wiki/STL_(file_format)',
u'UTTypeTagSpecification': {u'public.filename-extension': [u'stl'], u'public.mime-type': [u'text/plain']}
},
{
u'UTTypeIdentifier': u'org.khronos.collada.digital-asset-exchange',
u'UTTypeConformsTo': [u'public.xml', u'public.audiovisual-content'],
u'UTTypeDescription': u'Digital Asset Exchange (DAE)',
u'UTTypeTagSpecification': {u'public.filename-extension': [u'dae'], u'public.mime-type': [u'model/vnd.collada+xml']}
}
]
}
OPTIONS = {
'argv_emulation': True,
'iconfile': 'Cura/resources/Cura.icns',
'includes': ['objc', 'Foundation'],
'resources': DATA_FILES,
'optimize': '2',
'plist': PLIST,
'bdist_base': 'scripts/darwin/build',
'dist_dir': 'scripts/darwin/dist'
}
setup(
name="Cura",
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app']
)
else:
import zipfile
try:
import cx_Freeze
except:
print "ERROR: You need cx-Freeze installed to build this package"
sys.exit(1)
freezeVersion = map(int, cx_Freeze.version.split('.'))
if freezeVersion[0] < 4 or freezeVersion[0] == 4 and freezeVersion[1] < 2:
print "ERROR: Your cx-Freeze version is too old to use with Cura."
sys.exit(1)
sys.path.append(os.path.abspath('cura_sf'))
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {
"silent": True,
"packages": [
'encodings.utf_8',
"OpenGL", "OpenGL.arrays", "OpenGL.platform", "OpenGL.GLU",
], "excludes": [
'Tkinter', 'tcl', 'cura_sf', 'fabmetheus_utilities', 'skeinforge_application', 'numpy',
], "include_files": [
('images', 'images'),
], "build_exe": 'freeze_build'}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
cx_Freeze.setup( name = "Cura",
version = "RC5",
description = "Cura",
options = {"build_exe": build_exe_options},
executables = [cx_Freeze.Executable("cura.py", base=base)])
m = cx_Freeze.ModuleFinder(excludes=["gui"])
m.IncludeFile(os.path.abspath("cura.py"))
m.IncludeFile(os.path.abspath("cura_sf/skeinforge_application/skeinforge_plugins/profile_plugins/extrusion.py"))
m.IncludeFile(os.path.abspath("cura_sf/fabmetheus_utilities/fabmetheus_tools/interpret_plugins/stl.py"))
m.IncludeFile(os.path.abspath("cura_sf/skeinforge_application/skeinforge_plugins/craft_plugins/export_plugins/static_plugins/gcode_small.py"))
for name in os.listdir("cura_sf/skeinforge_application/skeinforge_plugins/craft_plugins"):
if name.endswith('.py'):
m.IncludeFile(os.path.abspath("cura_sf/skeinforge_application/skeinforge_plugins/craft_plugins/" + name))
m.ReportMissingModules()
cwd = os.path.abspath(".")
z = zipfile.ZipFile("freeze_build/cura_sf.zip", "w", zipfile.ZIP_DEFLATED)
for mod in m.modules:
if mod.file != None and mod.file.startswith(cwd):
if mod.file[len(cwd)+1:] == "cura.py":
z.write(mod.file[len(cwd)+1:], "__main__.py")
else:
z.write(mod.file[len(cwd)+1:])
z.write('cura_sf/fabmetheus_utilities/templates/layer_template.svg')
z.write('cura_sf/fabmetheus_utilities/version.txt')
z.write('__init__.py')
z.close()
|
Python
| 0 |
@@ -787,25 +787,21 @@
ank': u'
-Alternate
+Owner
',%0A
@@ -996,33 +996,29 @@
lerRank': u'
-Alternate
+Owner
'%0A
@@ -1305,17 +1305,13 @@
: u'
-Alternate
+Owner
'%0A
|
dcedefebd46a80f18372e045e3e4869bb4c88d89
|
Remove all tests from setup.py except those of gloo.gl
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
""" Vispy setup script.
Steps to do a new release:
Preparations:
* Test on Windows, Linux, Mac
* Make release notes
* Update API documentation and other docs that need updating.
Test installation:
* clear the build and dist dir (if they exist)
* python setup.py register -r http://testpypi.python.org/pypi
* python setup.py sdist upload -r http://testpypi.python.org/pypi
* pip install -i http://testpypi.python.org/pypi
Define the version:
* update __version__ in __init__.py
* Tag the tip changeset as version x.x
Generate and upload package (preferably on Windows)
* python setup.py register
* python setup.py sdist upload
* python setup.py bdist_wininst upload
Announcing:
* It can be worth waiting a day for eager users to report critical bugs
* Announce in scipy-user, vispy mailing list, G+
"""
import os
from os import path as op
try:
# use setuptools namespace, allows for "develop"
import setuptools # noqa, analysis:ignore
except ImportError:
pass # it's not essential for installation
from distutils.core import setup
name = 'vispy'
description = 'Interactive visualization in Python'
# Get version and docstring
__version__ = None
__doc__ = ''
docStatus = 0 # Not started, in progress, done
initFile = os.path.join(os.path.dirname(__file__), 'vispy', '__init__.py')
for line in open(initFile).readlines():
if (line.startswith('__version__')):
exec(line.strip())
elif line.startswith('"""'):
if docStatus == 0:
docStatus = 1
line = line.lstrip('"')
elif docStatus == 1:
docStatus = 2
if docStatus == 1:
__doc__ += line
setup(
name=name,
version=__version__,
author='Vispy contributors',
author_email='[email protected]',
license='(new) BSD',
url='http://vispy.org',
download_url='https://pypi.python.org/pypi/vispy',
keywords="visualization OpenGl ES medical imaging 3D plotting "
"numpy bigdata",
description=description,
long_description=__doc__,
platforms='any',
provides=['vispy'],
install_requires=[
'numpy',
'PyOpenGl'],
packages=[
'vispy',
'vispy.app', 'vispy.app.tests',
'vispy.app.backends',
'vispy.gloo', 'vispy.gloo.tests',
'vispy.gloo.gl', 'vispy.gloo.gl.tests',
'vispy.scene', 'vispy.scene.tests',
'vispy.scene.systems',
'vispy.scene.entities',
'vispy.scene.cameras',
'vispy.shaders',
'vispy.util', 'vispy.util.tests',
'vispy.util.dataio',
'vispy.visuals',
],
package_dir={
'vispy': 'vispy'},
package_data={
'vispy': [op.join('data', '*'),
op.join('app', 'tests', 'qt-designer.ui')]},
zip_safe=False,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'Intended Audience :: Education',
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering :: Visualization',
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
],
)
|
Python
| 0 |
@@ -2352,16 +2352,17 @@
y.app',
+#
'vispy.a
@@ -2364,32 +2364,32 @@
spy.app.tests',%0A
-
'vispy.a
@@ -2424,16 +2424,17 @@
.gloo',
+#
'vispy.g
@@ -2516,16 +2516,17 @@
scene',
+#
'vispy.s
@@ -2653,24 +2653,24 @@
y.shaders',%0A
-
'vis
@@ -2675,24 +2675,25 @@
ispy.util',
+#
'vispy.util.
|
e0efdff7380101437c75ce6a50dd93302a3315e2
|
Increase version dependency.
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
version='0.9'
setup(
name='pyres',
version=version,
description='Python resque clone',
author='Matt George',
author_email='[email protected]',
maintainer='Matt George',
license='MIT',
url='http://github.com/binarydud/pyres',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
download_url='http://cloud.github.com/downloads/binarydud/pyres/pyres-%s.tar.gz' % version,
include_package_data=True,
package_data={'resweb': ['templates/*.mustache','media/*']},
scripts=[
'scripts/pyres_worker',
'scripts/pyres_web',
'scripts/pyres_scheduler',
'scripts/pyres_manager'],
install_requires=[
'simplejson>=2.0.9',
'itty>=0.6.2',
'redis==1.34.1',
'pystache>=0.1.0',
'setproctitle==1.0'
],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python'],
)
|
Python
| 0 |
@@ -41,13 +41,9 @@
ges%0A
-
%0A
+
vers
@@ -603,17 +603,16 @@
worker',
-
%0A
@@ -632,17 +632,16 @@
es_web',
-
%0A
@@ -791,17 +791,17 @@
'redis
-=
+%3E
=1.34.1'
@@ -1166,9 +1166,10 @@
thon'%5D,%0A
-
)
+%0A
|
8781799d2511dbafa7b11f2f8fb45356031a619b
|
Bump the sqlalchemy-citext version requirement
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# Copyright 2013 Donald Stufft
#
# 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.
from __future__ import absolute_import, division, print_function
from setuptools import setup, find_packages
about = {}
with open("warehouse/__about__.py") as fp:
exec(fp.read(), about)
setup(
name=about["__title__"],
version=about["__version__"],
description=about["__summary__"],
long_description=open("README.rst").read(),
license=about["__license__"],
url=about["__uri__"],
author=about["__author__"],
author_email=about["__email__"],
classifiers=[
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
packages=find_packages(),
package_data={
"warehouse": ["*.yml"],
"warehouse.legacy": ["templates/*.html"],
"warehouse.migrations": ["*.mako", "versions/*.py"],
},
install_requires=[
"alembic",
"Jinja2",
"psycopg2cffi-compat>=1.1",
"PyYAML",
"six",
"SQLAlchemy",
"sqlalchemy-citext>=1.1.0",
"Werkzeug",
],
entry_points={
"console_scripts": [
"warehouse = warehouse.__main__:main",
],
},
zip_safe=False,
)
|
Python
| 0.000001 |
@@ -1963,17 +1963,17 @@
text%3E=1.
-1
+2
.0%22,%0A
|
18d899f36a140e677637118039e245127b0d138a
|
remove the long description
|
setup.py
|
setup.py
|
from os.path import dirname, join
from setuptools import setup, find_packages
from tvrenamr import get_version
def fread(fname):
return open(join(dirname(__file__), fname)).read()
setup(
name = 'tvrenamr',
version = get_version(),
description = 'Rename tv show files using online databases',
long_description = fread('README.markdown'),
author = 'George Hickman',
author_email = '[email protected]',
url = 'http://github.com/ghickman/tvrenamr',
license = 'MIT',
packages = find_packages(exclude=['tests']),
entry_points = {'console_scripts': ['tvr = tvrenamr.tvrenamr:run',],},
classifiers = [
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6',
'Topic :: Multimedia',
'Topic :: Utilities',
'Natural Language :: English'],
install_requires = ('lxml', 'pyyaml',)
)
|
Python
| 1 |
@@ -1,38 +1,4 @@
-from os.path import dirname, join%0A
from
@@ -76,82 +76,8 @@
on%0A%0A
-def fread(fname):%0A return open(join(dirname(__file__), fname)).read()%0A%0A
setu
@@ -200,57 +200,8 @@
s',%0A
- long_description = fread('README.markdown'),%0A
|
934e73247156b28d919957d738d8a5b03e403160
|
Add setup.py.
|
setup.py
|
setup.py
|
Python
| 0 |
@@ -0,0 +1,342 @@
+%22%22%22%0Asetup.py for simple_img_gallery.%0A%22%22%22%0A%0Afrom distutils.core import setup%0A%0Asetup(name=%22simple_img_gallery%22,%0A version=%220.0.1%22,%0A description=%22Simple image gallery generation.%22,%0A author=%22Pete Florence%22,%0A author_email=%22%22,%0A url=%22https://github.com/peteflorence/simple_img_gallery%22,%0A scripts=%5B'generate_gallery.py'%5D)%0A
|
|
52f679b0485a10176e0ac71dfbe0940baf4171ef
|
Update setup.py classifiers and imports [ci skip]
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# Don't use __future__ in this script, it breaks buildout
# from __future__ import print_function
import os
import subprocess
import sys
import shutil
from setuptools import setup, find_packages
from setuptools.command.install import install
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
with open('requirements.txt', 'r') as fh:
dependencies = [l.strip() for l in fh]
extras = {}
with open('requirements-extras.txt', 'r') as fh:
extras['extras'] = [l.strip() for l in fh][1:]
# Alternative name.
extras['full'] = extras['extras']
with open('requirements-tests.txt', 'r') as fh:
extras['tests'] = [l.strip() for l in fh][1:]
# ########## platform specific stuff #############
if sys.version_info[0] == 2 and sys.version_info[1] < 7:
raise Exception('Python 2 version < 2.7 is not supported')
elif sys.version_info[0] == 3 and sys.version_info[1] < 3:
raise Exception('Python 3 version < 3.3 is not supported')
##################################################
# Provided as an attribute, so you can append to these instead
# of replicating them:
standard_exclude = ('*.pyc', '*$py.class', '*~', '.*', '*.bak')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build',
'./dist', 'EGG-INFO', '*.egg-info')
def copy_messages():
themes_directory = os.path.join(
os.path.dirname(__file__), 'nikola', 'data', 'themes')
original_messages_directory = os.path.join(
themes_directory, 'default', 'messages')
for theme in ('orphan', 'monospace'):
theme_messages_directory = os.path.join(
themes_directory, theme, 'messages')
if os.path.exists(theme_messages_directory):
shutil.rmtree(theme_messages_directory)
shutil.copytree(original_messages_directory, theme_messages_directory)
def expands_symlinks_for_windows():
"""replaces the symlinked files with a copy of the original content.
In windows (msysgit), a symlink is converted to a text file with a
path to the file it points to. If not corrected, installing from a git
clone will end with some files with bad content
After install the working copy will be dirty (symlink markers overwritten
with real content)
"""
if sys.platform != 'win32':
return
# apply the fix
localdir = os.path.dirname(os.path.abspath(__file__))
oldpath = sys.path[:]
sys.path.insert(0, os.path.join(localdir, 'nikola'))
winutils = __import__('winutils')
failures = winutils.fix_all_git_symlinked(localdir)
sys.path = oldpath
del sys.modules['winutils']
if failures != -1:
print('WARNING: your working copy is now dirty by changes in '
'samplesite, sphinx and themes')
if failures > 0:
raise Exception("Error: \n\tnot all symlinked files could be fixed." +
"\n\tYour best bet is to start again from clean.")
def remove_old_files(self):
tree = os.path.join(self.install_lib, 'nikola')
try:
shutil.rmtree(tree, ignore_errors=True)
except:
pass
class nikola_install(install):
def run(self):
expands_symlinks_for_windows()
remove_old_files(self)
install.run(self)
setup(name='Nikola',
version='7.7.9',
description='A modular, fast, simple, static website and blog generator',
long_description=open('README.rst').read(),
author='Roberto Alsina and others',
author_email='[email protected]',
url='https://getnikola.com/',
packages=find_packages(exclude=('tests',)),
license='MIT',
keywords='website, blog, static',
classifiers=('Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Plugins',
'Environment :: Web Environment',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: OS Independent',
'Operating System :: POSIX',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Text Processing :: Markup'),
install_requires=dependencies,
extras_require=extras,
tests_require=['pytest'],
include_package_data=True,
cmdclass={'install': nikola_install, 'test': PyTest},
data_files=[
('share/doc/nikola', [
'docs/manual.txt',
'docs/theming.txt',
'docs/extending.txt']),
('share/man/man1', ['docs/man/nikola.1.gz']),
],
entry_points={
'console_scripts': [
'nikola = nikola.__main__:main'
]
},
)
|
Python
| 0 |
@@ -128,26 +128,8 @@
os%0A
-import subprocess%0A
impo
@@ -4374,16 +4374,75 @@
MacOS',%0A
+ 'Operating System :: MacOS :: MacOS X',%0A
|
ff5c68ccd566ba388f919bb663c5055685be3070
|
Add initial setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001 |
@@ -0,0 +1,705 @@
+#!/usr/bin/env python%0A%0Afrom setuptools import setup%0A%0Asetup(%0A name='mdx_picture',%0A version='1.0',%0A author='Artem Grebenkin',%0A author_email='[email protected]',%0A description='Python-Markdown extension supports the %3Cpicture%3E tag.',%0A url='http://www.artemgrebenkin.com/',%0A py_modules=%5B'mdx_picture'%5D,%0A install_requires=%5B'Markdown%3E=2.0'%5D,%0A classifiers=%5B%0A 'Development Status :: 4 - Beta',%0A 'License :: OSI Approved :: BSD License',%0A 'Intended Audience :: Developers',%0A 'Environment :: Web Environment',%0A 'Programming Language :: Python',%0A 'Topic :: Text Processing :: Filters',%0A 'Topic :: Text Processing :: Markup :: HTML'%0A %5D%0A)%0A
|
|
6972c0a6fc0431c7e41b110ea8c41dd9a4ed076c
|
Add distutils setup script
|
setup.py
|
setup.py
|
Python
| 0 |
@@ -0,0 +1,375 @@
+#!/usr/bin/env python3%0A%0Afrom distutils.core import setup%0A%0Asetup(%0A%09name='python-fsb5',%0A%09version='1.0',%0A%09author='Simon Pinfold',%0A%09author_email='[email protected]',%0A%09description='Library and to extract audio from FSB5 (FMOD Sample Bank) files',%0A%09download_url='https://github.com/synap5e/python-fsb5/tarball/master',%0A%09license='MIT',%0A%09url='https://github.com/synap5e/python-fsb5',%0A)%0A
|
|
0bf30432084a5b6e71ea2ac36af165f7c4cee133
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001 |
@@ -0,0 +1,920 @@
+#!/usr/bin/env python%0A%0Afrom setuptools import setup%0A%0Asetup(name='acapi',%0A version='0.1',%0A description='Acquia Cloud API client.',%0A author='Dave Hall',%0A author_email='[email protected]',%0A url='http://github.com/skwashd/python-acquia-cloud',%0A install_requires=%5B'httplib2==0.9', 'simplejson==3.5.3', 'six==1.7.3'%5D,%0A license='MIT',%0A classifiers=%5B%0A 'Development Status :: 3 - Alpha',%0A 'Topic :: Internet',%0A 'Intended Audience :: Developers',%0A 'License :: OSI Approved :: MIT License',%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python',%0A 'Programming Language :: Python :: 2',%0A 'Programming Language :: Python :: 2.7',%0A %5D,%0A packages=%5B%0A 'acapi',%0A 'acapi.compat',%0A 'acapi.resources',%0A %5D,%0A )%0A
|
|
3a235f8525ae89ae91c333f7cd10ed307c33011c
|
Exclude local data from package.
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name = "django-forms-builder",
version = __import__("forms_builder").__version__,
author = "Stephen McDonald",
author_email = "[email protected]",
description = ("A Django reusable app providing the ability for admin "
"users to create their own forms."),
long_description = open("README.rst").read(),
url = "http://github.com/stephenmcd/django-forms-builder",
zip_safe = False,
include_package_data = True,
packages = find_packages(),
install_requires = [
"sphinx-me >= 0.1.2",
"django-email-extras >= 0.1.7",
"django",
],
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: Site Management",
]
)
|
Python
| 0 |
@@ -3,56 +3,611 @@
rom
-setuptools import setup, find_packages%0A%0A%0Asetup(%0A
+__future__ import with_statement%0Aimport os%0Afrom setuptools import setup, find_packages%0A%0A%0Aexclude = %5B%22forms_builder/example_project/dev.db%22,%0A %22forms_builder/example_project/local_settings.py%22%5D%0Aexclude = dict(%5B(e, None) for e in exclude%5D)%0Afor e in exclude:%0A if e.endswith(%22.py%22):%0A try:%0A os.remove(%22%25sc%22 %25 e)%0A except:%0A pass%0A try:%0A with open(e, %22r%22) as f:%0A exclude%5Be%5D = (f.read(), os.stat(e))%0A os.remove(e)%0A except Exception, e:%0A import pdb; pdb.set_trace()%0A pass%0Aimport pdb; pdb.set_trace()%0A%0Atry:%0A setup(%0A
@@ -641,16 +641,20 @@
r%22,%0A
+
+
version
@@ -696,16 +696,20 @@
sion__,%0A
+
auth
@@ -733,24 +733,28 @@
onald%22,%0A
+
+
author_email
@@ -780,16 +780,20 @@
l.com%22,%0A
+
desc
@@ -868,16 +868,20 @@
+
+
%22users t
@@ -909,16 +909,20 @@
rms.%22),%0A
+
long
@@ -967,16 +967,20 @@
(),%0A
+
+
url = %22h
@@ -1026,24 +1026,28 @@
s-builder%22,%0A
+
zip_safe
@@ -1060,16 +1060,20 @@
se,%0A
+
+
include_
@@ -1097,16 +1097,20 @@
ue,%0A
+
+
packages
@@ -1133,16 +1133,20 @@
(),%0A
+
+
install_
@@ -1154,24 +1154,28 @@
equires = %5B%0A
+
%22sph
@@ -1196,24 +1196,28 @@
2%22,%0A
+
+
%22django-emai
@@ -1240,24 +1240,28 @@
7%22,%0A
+
%22django%22,%0A
@@ -1266,11 +1266,19 @@
+
+
%5D,%0A
+
@@ -1301,16 +1301,20 @@
+
%22Develop
@@ -1352,16 +1352,20 @@
table%22,%0A
+
@@ -1406,16 +1406,20 @@
+
%22Intende
@@ -1445,16 +1445,20 @@
opers%22,%0A
+
@@ -1503,16 +1503,20 @@
+
%22Program
@@ -1541,16 +1541,20 @@
ython%22,%0A
+
@@ -1576,32 +1576,36 @@
jango%22,%0A
+
%22Topic :: Intern
@@ -1640,32 +1640,36 @@
ntent%22,%0A
+
+
%22Topic :: Intern
@@ -1712,8 +1712,346 @@
-%5D%0A)
+ %5D%0A )%0Afinally:%0A for e in exclude:%0A if exclude%5Be%5D is not None:%0A data, stat = exclude%5Be%5D%0A try:%0A with open(e, %22w%22) as f:%0A f.write(data)%0A os.chown(e, stat.st_uid, stat.st_gid)%0A os.chmod(e, stat.st_mode)%0A except:%0A pass
%0A
|
0cdc580b5021448497ba78fce2e93f45500c2e24
|
version bump
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='withings',
version='0.2',
description="Library for the Withings API",
author='Maxime Bouroumeau-Fuseau',
author_email='[email protected]',
url="https://github.com/maximebf/python-withings",
license = "MIT License",
packages = ['withings'],
install_requires = ['requests', 'requests-oauth'],
scripts=['bin/withings'],
keywords="withings",
zip_safe = True
)
|
Python
| 0.000001 |
@@ -92,9 +92,9 @@
='0.
-2
+3
',%0A
|
3aa467f1af903e9c21029c50519c4986cea66fee
|
remove comment
|
corehq/apps/app_manager/detail_screen.py
|
corehq/apps/app_manager/detail_screen.py
|
from corehq.apps.app_manager import suite_xml as sx, xform
def get_column_generator(app, module, detail, column):
return get_class_for_format(column.format)(app, module, detail, column)
def get_class_for_format(slug):
return get_class_for_format._format_map.get(slug, FormattedDetailColumn)
get_class_for_format._format_map = {}
class register_format_type(object):
def __init__(self, slug):
self.slug = slug
def __call__(self, klass):
get_class_for_format._format_map[self.slug] = klass
return klass
class FormattedDetailColumn(object):
header_width = None
template_width = None
template_form = None
def __init__(self, app, module, detail, column):
from corehq.apps.app_manager.suite_xml import IdStrings
self.app = app
self.module = module
self.detail = detail
self.column = column
self.id_strings = IdStrings()
@property
def locale_id(self):
return self.id_strings.detail_column_header_locale(self.module, self.detail, self.column)
@property
def header(self):
header = sx.Header(
text=sx.Text(locale_id=self.locale_id),
width=self.header_width
)
return header
variables = None
@property
def template(self):
template = sx.Template(
text=sx.Text(xpath_function=self.xpath_function),
form=self.template_form,
width=self.template_width,
)
if self.variables:
for key, value in sorted(self.variables.items()):
template.text.xpath.variables.node.append(
sx.XpathVariable(name=key, locale_id=value).node
)
return template
@property
def xpath(self):
return self.column.xpath
XPATH_FUNCTION = u"{xpath}"
def evaluate_template(self, template):
if template:
return template.format(
xpath=self.xpath,
app=self.app,
module=self.module,
detail=self.detail,
column=self.column
)
@property
def xpath_function(self):
return self.evaluate_template(self.XPATH_FUNCTION)
@property
def hidden_header(self):
return sx.Header(
text=sx.Text(),
width=0,
)
@property
def hidden_template(self):
return sx.Template(
text=sx.Text(xpath_function=self.sort_xpath_function),
width=0,
)
SORT_XPATH_FUNCTION = None
@property
def sort_xpath_function(self):
return self.evaluate_template(self.SORT_XPATH_FUNCTION)
@property
def fields(self):
if self.sort_xpath_function and self.detail.display == 'short':
yield sx.Field(
header=self.header,
template=self.hidden_template,
)
yield sx.Field(
header=self.hidden_header,
template=self.template,
)
else:
yield sx.Field(
header=self.header,
template=self.template,
)
class HideShortHeaderColumn(FormattedDetailColumn):
@property
def header_width(self):
if self.detail.display == 'short':
return 0
class HideShortColumn(HideShortHeaderColumn):
@property
def template_width(self):
if self.detail.display == 'short':
return 0
"""
{value: "plain", label: DetailScreenConfig.message.PLAIN_FORMAT},
{value: "date", label: DetailScreenConfig.message.DATE_FORMAT},
{value: "time-ago", label: DetailScreenConfig.message.TIME_AGO_FORMAT},
{value: "phone", label: DetailScreenConfig.message.PHONE_FORMAT},
{value: "enum", label: DetailScreenConfig.message.ENUM_FORMAT},
{value: "late-flag", label: DetailScreenConfig.message.LATE_FLAG_FORMAT},
{value: "invisible", label: DetailScreenConfig.message.INVISIBLE_FORMAT},
{value: "filter", label: DetailScreenConfig.message.FILTER_XPATH_FORMAT},
{value: "address", label: DetailScreenConfig.message.ADDRESS_FORMAT}
Format types not supported in the UI:
advanced
enum-image
"""
@register_format_type('plain')
class Plain(FormattedDetailColumn):
pass
@register_format_type('date')
class Date(FormattedDetailColumn):
XPATH_FUNCTION = u"if({xpath} = '', '', format_date(date(if({xpath} = '', 0, {xpath})),'short'))"
SORT_XPATH_FUNCTION = u"{xpath}"
@register_format_type('time-ago')
class TimeAgo(FormattedDetailColumn):
XPATH_FUNCTION = u"if({xpath} = '', '', string(int((today() - date({xpath})) div {column.time_ago_interval})))"
@register_format_type('phone')
class Phone(FormattedDetailColumn):
@property
def template_form(self):
if self.detail.display == 'long':
return 'phone'
@register_format_type('enum')
class Enum(FormattedDetailColumn):
@property
def xpath_function(self):
parts = []
for key in self.column.enum:
parts.append(
u"if({xpath} = '{key}', $k{key}, ".format(key=key, xpath=self.xpath)
)
parts.append("''")
parts.append(")" * len(self.column.enum))
return ''.join(parts)
@property
def variables(self):
variables = {}
for key in self.column.enum:
v_key = u"k{key}".format(key=key)
v_val= self.id_strings.detail_column_enum_variable(self.module, self.detail, self.column, key)
variables[v_key] = v_val
return variables
@register_format_type('late-flag')
class LateFlag(HideShortHeaderColumn):
template_width = "10%"
XPATH_FUNCTION = u"if({xpath} = '', '*', if(today() - date({xpath}) > {column.late_flag}, '*', ''))"
@register_format_type('invisible')
class Invisible(HideShortColumn):
pass
@register_format_type('filter')
class Filter(HideShortColumn):
@property
def fields(self):
return []
@property
def filter_xpath(self):
return self.column.filter_xpath.replace('.', self.xpath)
@register_format_type('address')
class Address(HideShortColumn):
template_form = 'address'
template_width = 0
# todo: These two were never actually supported, and 'advanced' certainly never worked
# but for some reason have been hanging around in the suite.xml template since September 2010
#
#@register_format_type('advanced')
#class Advanced(HideShortColumn):
# pass
#
#@register_format_type('enum-image')
#class EnumImage(HideShortColumn):
# template_form = 'image'
|
Python
| 0 |
@@ -3493,697 +3493,8 @@
n 0%0A
-%22%22%22%0A%7Bvalue: %22plain%22, label: DetailScreenConfig.message.PLAIN_FORMAT%7D,%0A%7Bvalue: %22date%22, label: DetailScreenConfig.message.DATE_FORMAT%7D,%0A%7Bvalue: %22time-ago%22, label: DetailScreenConfig.message.TIME_AGO_FORMAT%7D,%0A%7Bvalue: %22phone%22, label: DetailScreenConfig.message.PHONE_FORMAT%7D,%0A%7Bvalue: %22enum%22, label: DetailScreenConfig.message.ENUM_FORMAT%7D,%0A%7Bvalue: %22late-flag%22, label: DetailScreenConfig.message.LATE_FLAG_FORMAT%7D,%0A%7Bvalue: %22invisible%22, label: DetailScreenConfig.message.INVISIBLE_FORMAT%7D,%0A%7Bvalue: %22filter%22, label: DetailScreenConfig.message.FILTER_XPATH_FORMAT%7D,%0A%7Bvalue: %22address%22, label: DetailScreenConfig.message.ADDRESS_FORMAT%7D%0A%0AFormat types not supported in the UI:%0Aadvanced%0Aenum-image%0A%22%22%22
%0A%0A@r
|
207116ee7ba8d8da521f497997da90066831a551
|
Add codemod to replace __unicode__ with __str__
|
django3_codemods/replace_unicode_with_str.py
|
django3_codemods/replace_unicode_with_str.py
|
Python
| 0.000001 |
@@ -0,0 +1,251 @@
+import sys%0A%0Afrom bowler import Query%0A%0A%0A(%0A Query(sys.argv%5B1%5D)%0A .select_function(%22__unicode__%22)%0A .rename('__str__')%0A .idiff()%0A),%0A(%0A Query(sys.argv%5B1%5D)%0A .select_method(%22__unicode__%22)%0A .is_call()%0A .rename('__str__')%0A .idiff()%0A)%0A
|
|
d85a68e36443bfcdeed2d8f1f3960d1596ef762a
|
Create catchtheball.py
|
catchtheball.py
|
catchtheball.py
|
Python
| 0.000007 |
@@ -0,0 +1,1325 @@
+import simplegui%0Aimport random%0A%0AFRAME_WIDTH=STAGE_WIDTH=GROUND_WIDTH=821%0AFRAME_HEIGHT=498%0ASTAGE_HEIGHT=FRAME_HEIGHT-30%0APADDLE_HEIGHT=STAGE_HEIGHT%0APADDLE_WIDTH=8%0APADDLE_POS=%5BSTAGE_WIDTH/2,PADDLE_HEIGHT%5D%0A%0Aimage=simplegui.load_image(%22http://mrnussbaum.com/calendarclowns1/images/game_background.png%22)%0A%0Alist_of_balls=%5B%5D%0A%0Acolors=%5B'Aqua','Blue','Fuchsia','Gray',%0A 'Green','Lime','Maroon','Navy','Olive',%0A 'Orange','Purple','Red','Silver','Teal',%0A 'White','Yellow'%5D%0A%0A%0Aclass Ball:%0A def __init__(self,color,radius,x_location):%0A self.radius=radius%0A self.color=color%0A self.location=%5Bx_location,0%5D%0A %0A%0Adef timer():%0A radius = 10%0A color = random.choice(colors)%0A x_location = random.randint(20, STAGE_WIDTH-20)%0A new_ball = Ball(color,radius, x_location)%0A list_of_balls.append(new_ball)%0A %0A %0Adef draw(canvas):%0A canvas.draw_image(image,%5BFRAME_WIDTH/2,FRAME_HEIGHT/2%5D,%5BFRAME_WIDTH,FRAME_HEIGHT%5D,%5BFRAME_WIDTH/2,FRAME_HEIGHT/2%5D,%5BFRAME_WIDTH,FRAME_HEIGHT%5D)%0A %0A for ball in list_of_balls:%0A ball.location%5B1%5D+=5%0A canvas.draw_circle(ball.location,ball.radius,10,ball.color,ball.color)%0A %0A %0Aframe=simplegui.create_frame(%22ball%22,FRAME_WIDTH,FRAME_HEIGHT)%0Atimer=simplegui.create_timer(2000,timer)%0Aframe.set_draw_handler(draw)%0Aframe.start()%0Atimer.start()%0A
|
|
54bb69cd3646246975f723923254549bc5f11ca0
|
Add default paver commands
|
citools/paver.py
|
citools/paver.py
|
Python
| 0.000001 |
@@ -0,0 +1,1786 @@
+@task%0A@consume_args%0A@needs('unit', 'integrate')%0Adef test():%0A %22%22%22 Run whole testsuite %22%22%22%0A%0Adef djangonize_test_environment(test_project_module):%0A%0A sys.path.insert(0, abspath(join(dirname(__file__))))%0A sys.path.insert(0, abspath(join(dirname(__file__), %22tests%22)))%0A sys.path.insert(0, abspath(join(dirname(__file__), %22tests%22, test_project_module)))%0A%0A os.environ%5B'DJANGO_SETTINGS_MODULE'%5D = %22%25s.settings%22 %25 test_project_module%0A%0Adef run_tests(test_project_module, nose_args):%0A djangonize_test_environment(test_project_module)%0A%0A import nose%0A%0A os.chdir(abspath(join(dirname(__file__), %22tests%22, test_project_module)))%0A%0A argv = %5B%22--with-django%22%5D + nose_args%0A%0A nose.run_exit(%0A argv = %5B%22nosetests%22%5D + argv,%0A defaultTest = test_project_module%0A )%0A%0A@task%0A@consume_args%0Adef unit(args):%0A %22%22%22 Run unittests %22%22%22%0A run_tests(test_project_module=%22unit_project%22, nose_args=%5B%5D+args)%0A%0A%0A@task%0A@consume_args%0Adef integrate(args):%0A %22%22%22 Run integration tests %22%22%22%0A run_tests(test_project_module=%22example_project%22, nose_args=%5B%22--with-selenium%22, %22--with-djangoliveserver%22%5D+args)%0A%0A%0A@task%0Adef install_dependencies():%0A sh('pip install --upgrade -r requirements.txt')%0A%0A@task%0Adef bootstrap():%0A options.virtualenv = %7B'packages_to_install' : %5B'pip'%5D%7D%0A call_task('paver.virtual.bootstrap')%0A sh(%22python bootstrap.py%22)%0A path('bootstrap.py').remove()%0A%0A%0A print '*'*80%0A if sys.platform in ('win32', 'winnt'):%0A print %22* Before running other commands, You now *must* run %25s%22 %25 os.path.join(%22bin%22, %22activate.bat%22)%0A else:%0A print %22* Before running other commands, You now *must* run source %25s%22 %25 os.path.join(%22bin%22, %22activate%22)%0A print '*'*80%0A%0A@task%0A@needs('install_dependencies')%0Adef prepare():%0A %22%22%22 Prepare complete environment %22%22%22%0A
|
|
0878c9224af57eea17c9b2c7f01d5fb0f5cfecfa
|
fix some pylint hints
|
utils/oscap_docker_python/get_cve_input.py
|
utils/oscap_docker_python/get_cve_input.py
|
# Copyright (C) 2015 Brent Baude <[email protected]>
#
# This library 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 of the License, or (at your option) any later version.
#
# This library 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 this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
try:
# Python2 imports
import urlparse
import urllib2 as urllib
except ImportError:
#Python3 imports
import urllib.parse as urlparse
import urllib.request as urllib
from os.path import join, exists
from os import stat, utime
from sys import stderr
import datetime
class getInputCVE(object):
'''
Class to obtain the CVE data provided by RH used to scan
for CVEs using openscap
'''
hdr = {'User-agent': 'Mozilla/5.0'}
hdr2 = [('User-agent', 'Mozilla/5.0')]
url = "http://www.redhat.com/security/data/oval/"
dist_cve_name = "Red_Hat_Enterprise_Linux_{0}.xml"
dists = [5, 6, 7]
remote_pattern = '%a, %d %b %Y %H:%M:%S %Z'
def __init__(self, fs_dest, DEBUG=False):
''' Simple init declaration '''
self.dest = fs_dest
self.DEBUG = DEBUG
def _fetch_single(self, dist):
'''
Given a distribution number (i.e. 7), it will fetch the
distribution specific data file if upstream has a newer
input file. Returns the path of file.
'''
cve_file = self.dist_cve_name.format(dist)
dest_file = join(self.dest, cve_file)
dist_url = (urlparse.urljoin(self.url, cve_file))
if self._is_cache_same(dest_file, dist_url):
return dest_file
_url = urllib.Request(dist_url, headers=self.hdr)
# TODO
# When dist specific files are available in bz form, some
# of this logic may need to change
try:
resp = urllib.urlopen(_url)
except Exception as url_error:
raise Exception("Unable to fetch CVE inputs due to"
.format(url_error))
fh = open(dest_file, "w")
fh.write(resp.read())
fh.close()
# Correct Last-Modified timestamp
headers = dict(resp.info())
resp.close()
try:
remote_ts = headers['last-modified']
epoch = datetime.datetime.utcfromtimestamp(0)
remote_dt = datetime.datetime.strptime(remote_ts, self.remote_pattern)
seconds_epoch = (remote_dt - epoch).total_seconds()
utime(dest_file, (seconds_epoch, seconds_epoch))
except KeyError:
stderr.write("Response header of HTTP doesn't contain" \
"\"last-modified\" field. Cannot determine version" \
" of remote file \"{0}\"".format(dist_url))
return dest_file
def _is_cache_same(self, dest_file, dist_url):
'''
Checks if the local cache version and the upstream
version is the same or not. If they are the same,
returns True; else False.
'''
if not exists(dest_file):
if self.DEBUG:
stderr.write("No file in cache, fetching {0}\n".format(dest_file))
return False
opener = urllib.OpenerDirector()
opener.add_handler(urllib.HTTPHandler())
opener.add_handler(urllib.HTTPDefaultErrorHandler())
# Extra for handling redirects
opener.add_handler(urllib.HTTPErrorProcessor())
opener.add_handler(urllib.HTTPRedirectHandler())
# Add the header
opener.addheaders = self.hdr2
# Grab the header
try:
res = opener.open(HeadRequest(dist_url))
headers = dict(res.info())
res.close()
remote_ts = headers['last-modified']
except urllib2.HTTPError as http_error:
if self.DEBUG:
stderr.write("Cannot send HTTP HEAD request to get \"last-modified\"" \
" attribute of remote content file.\n{0} - {1}\n"
.format(http_error.code, http_error.reason))
return False
except KeyError:
if self.DEBUG:
stderr.write("Response header of HTTP doesn't contain" \
"\"last-modified\" field. Cannot determine version" \
" of remote file \"{0}\"".format(dist_url))
return False
# The remote's datetime
remote_dt = datetime.datetime.strptime(remote_ts, self.remote_pattern)
# Get the locals datetime from the file's mtime, converted to UTC
local_dt = datetime.datetime.utcfromtimestamp((stat(dest_file))
.st_mtime)
# Giving a two second comfort zone
# Else we declare they are different
if (remote_dt - local_dt).seconds > 2:
if self.DEBUG:
stderr.write("Had a local file {0} " \
"but it wasn't new enough\n".format(dest_file))
return False
if self.DEBUG:
stderr.write("File {0} is same as upstream\n".format(dest_file))
return True
def fetch_dist_data(self):
'''
Fetches all the the distribution specific data used for
input with openscap cve scanning and returns a list
of those files.
'''
cve_files = []
for dist in self.dists:
cve_files.append(self._fetch_single(dist))
return cve_files
class HeadRequest(urllib.Request):
def get_method(self):
return 'HEAD'
|
Python
| 0.000005 |
@@ -2410,16 +2410,20 @@
s due to
+ %7B0%7D
%22%0A
@@ -4189,32 +4189,33 @@
last-modified'%5D%0A
+%0A
except u
@@ -4219,17 +4219,16 @@
t urllib
-2
.HTTPErr
@@ -4382,16 +4382,23 @@
+
%22 attrib
@@ -4439,16 +4439,23 @@
%7B1%7D%5Cn%22%0A
+
@@ -5847,20 +5847,16 @@
.dists:%0A
-
|
0575a141153fb07a5f03c0681cdf727450348fc0
|
Create space.py
|
space.py
|
space.py
|
Python
| 0.001193 |
@@ -0,0 +1,728 @@
+def ParentOf(n, arr):%0A if arr%5Bn%5D == n:%0A return n%0A else:%0A return ParentOf(arr%5Bn%5D,arr)%0A%0An, p = list(map(int, input().split()))%0Aarr = %5B%5D%0Afor t in range(0,n):%0A arr.append(t)%0A%0Afor q in range(p):%0A #Quick Union the line%0A first, sec = list(map(int,input().split()))%0A arr%5Bfirst%5D = ParentOf(sec)%0A %0A#Get number of people in each group%0Agroups = %5B%5D%0Afor q in range(0,n):%0A groups%5Bq%5D = arr.count(q)%0A %0A %0A#groups is accurate if 0's removed%0AtrueG = %5B%5D%0Afor t in groups:%0A if t != 0:%0A trueG.append(t)%0A %0Aways = 0%0Afor index, a in enumerate(trueG):%0A i = index + 1%0A while i %3C len(trueG):%0A ways += a * trueG%5Bi%5D%0A i += 1%0A %0Aprint(str(ways))%0A %0A %0A %0A %0A %0A
|
|
3c074ab5c630590ca32f8951eecb3087afd8ae01
|
add solution for Binary Tree Level Order Traversal II
|
src/binaryTreeLevelOrderTraversalII.py
|
src/binaryTreeLevelOrderTraversalII.py
|
Python
| 0 |
@@ -0,0 +1,660 @@
+# Definition for a binary tree node%0A# class TreeNode:%0A# def __init__(self, x):%0A# self.val = x%0A# self.left = None%0A# self.right = None%0A%0A%0Aclass Solution:%0A # @param root, a tree node%0A # @return a list of lists of integers%0A%0A def levelOrderBottom(self, root):%0A self.res = %5B%5D%0A self._dfs(root, 0)%0A return reversed(self.res)%0A%0A def _dfs(self, root, level):%0A if not root:%0A return%0A if len(self.res) == level:%0A self.res.append(%5Broot.val%5D)%0A else:%0A self.res%5Blevel%5D.append(root.val)%0A self._dfs(root.left, level+1)%0A self._dfs(root.right, level+1)%0A
|
|
79cf7834c4a92f84c3595af302c7b0bfa09331f2
|
word2vec basic
|
Experiments/Tensorflow/Neural_Networks/logic_gate_linear_regressor.py
|
Experiments/Tensorflow/Neural_Networks/logic_gate_linear_regressor.py
|
Python
| 0.999103 |
@@ -0,0 +1,2603 @@
+'''%0ALogical Operation by 2-layer Neural Networks (using TF Layers) on TensorFlow%0AAuthor: Rowel Atienza%0AProject: https://github.com/roatienza/Deep-Learning-Experiments%0A'''%0A# On command line: python3 logic_gate_linear_regressor.py%0A# Prerequisite: tensorflow 1.0 (see tensorflow.org)%0A%0Afrom __future__ import print_function%0A%0Aimport tensorflow as tf%0Aimport numpy as np%0Aimport tensorflow.contrib.learn as learn%0Afrom tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn%0Atf.logging.set_verbosity(tf.logging.INFO)%0A%0Alearning_rate = 0.01%0A# try other values for nhidden%0Anhidden = 16%0A%0Adef fnn_model_fn(features,labels,mode):%0A print(features)%0A print(labels)%0A # output_labels = tf.reshape(labels,%5B-1,1%5D)%0A dense = tf.layers.dense(features,units=nhidden,activation=tf.nn.relu,use_bias=True)%0A print(dense)%0A logits = tf.layers.dense(dense,units=1,use_bias=True)%0A print(logits)%0A onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=1)%0A if mode != learn.ModeKeys.EVAL:%0A # loss = tf.losses.sigmoid_cross_entropy(output_labels,logits)%0A # loss = tf.losses.mean_squared_error(labels=output_labels,predictions=logits)%0A loss = tf.losses.softmax_cross_entropy(%0A onehot_labels=onehot_labels, logits=logits)%0A if mode==learn.ModeKeys.TRAIN:%0A train_op = tf.contrib.layers.optimize_loss(%0A loss=loss,%0A global_step=tf.contrib.framework.get_global_step(),%0A learning_rate=learning_rate,%0A optimizer=%22SGD%22)%0A predictions = %7B%0A %22classes%22: tf.round(logits),%0A %22probabilities%22: tf.nn.softmax(%0A logits, name=%22softmax_tensor%22)%0A %7D%0A return model_fn.ModelFnOps(%0A mode=mode, predictions=predictions, loss=loss, train_op=train_op)%0A%0A%0Adef main(arg):%0A x_data = np.array(%5B%5B0, 0%5D, %5B0, 1%5D, %5B1, 0%5D, %5B1, 1%5D%5D, dtype=np.float32)%0A # try other logics; xor = %5B0., 1., 1., 0.%5D, or = %5B0., 1., 1., 1.%5D, and = %5B0., 0., 0., 1.%5D, etc%0A y_data = np.array(%5B%5B0%5D, %5B1%5D, %5B1%5D, %5B0%5D%5D, dtype=np.float32)%0A classifier = learn.Estimator(model_fn=fnn_model_fn, model_dir=%22/tmp/fnn%22)%0A to_log = %7B%22probabilities%22: %22softmax_tensor%22%7D%0A log_hook = tf.train.LoggingTensorHook(to_log, every_n_iter=10)%0A classifier.fit(x=x_data, y=y_data, batch_size=1, steps=50, monitors=%5Blog_hook%5D)%0A metrics = %7B%0A %22accuracy%22:%0A learn.MetricSpec(%0A metric_fn=tf.metrics.accuracy, prediction_key=%22classes%22),%0A %7D%0A%0A eval_results = classifier.evaluate(%0A x=x_data, y=y_data, metrics=metrics)%0A print(eval_results)%0A%0Aif __name__ == %22__main__%22:%0A tf.app.run()%0A
|
|
f22b6368bdfe91cff06ede51c1caad04f769b437
|
add management command to load location type into supply point
|
custom/colalife/management/commands/load_location_type_into_supply_point.py
|
custom/colalife/management/commands/load_location_type_into_supply_point.py
|
Python
| 0 |
@@ -0,0 +1,603 @@
+from corehq.apps.commtrack.models import SupplyPointCase%0Afrom corehq.apps.locations.models import Location%0Afrom django.core.management import BaseCommand%0A%0A%0Aclass Command(BaseCommand):%0A help = 'Store location type with supply point.'%0A%0A def handle(self, *args, **options):%0A for location_type in %5B%22wholesaler%22, %22retailer%22%5D:%0A for location in Location.filter_by_type(%22colalifezambia%22, location_type):%0A supply_point_case = SupplyPointCase.get_by_location(location)%0A supply_point_case.location_type = location_type%0A supply_point_case.save()%0A
|
|
3e02fe79f4fad6f5252af750a13d74d7a4f82cc5
|
read in the file, probably badly
|
src/emc/usr_intf/touchy/filechooser.py
|
src/emc/usr_intf/touchy/filechooser.py
|
# Touchy is Copyright (c) 2009 Chris Radek <[email protected]>
#
# Touchy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Touchy 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.
import dircache
import os
class filechooser:
def __init__(self, gtk, emc, labels, eventboxes, program):
self.labels = labels
self.eventboxes = eventboxes
self.numlabels = len(labels)
self.program = program
self.gtk = gtk
self.emc = emc
self.emccommand = emc.command()
self.fileoffset = 0
self.dir = os.path.join(os.getenv('HOME'), 'emc2', 'nc_files')
self.files = dircache.listdir(self.dir)
self.selected = -1
self.populate()
def populate(self):
files = self.files[self.fileoffset:]
for i in range(self.numlabels):
l = self.labels[i]
e = self.eventboxes[i]
if i < len(files):
l.set_text(files[i])
else:
l.set_text('')
if self.selected == self.fileoffset + i:
e.modify_bg(self.gtk.STATE_NORMAL, self.gtk.gdk.color_parse('#fff'))
else:
e.modify_bg(self.gtk.STATE_NORMAL, self.gtk.gdk.color_parse('#ccc'))
def select(self, eventbox, event):
n = int(eventbox.get_name()[20:])
self.selected = self.fileoffset + n
self.emccommand.mode(self.emc.MODE_MDI)
self.emccommand.program_open(os.path.join(self.dir, self.labels[n].get_text()))
self.populate()
def up(self, b):
self.fileoffset -= self.numlabels
if self.fileoffset < 0:
self.fileoffset = 0
self.populate()
def down(self, b):
self.fileoffset += self.numlabels
self.populate()
|
Python
| 0.000001 |
@@ -1788,37 +1788,13 @@
-self.emccommand.program_open(
+fn =
os.p
@@ -1838,16 +1838,135 @@
_text())
+%0A f = file(fn, 'r')%0A self.lines = f.readlines()%0A f.close()%0A self.emccommand.program_open(fn
)%0A
|
37793ec10e2b27e64efaa3047ae89a6d10a6634d
|
Update urlrewrite_redirect.py
|
flexget/plugins/urlrewrite_redirect.py
|
flexget/plugins/urlrewrite_redirect.py
|
from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('urlrewrite_redirect')
class UrlRewriteRedirect(object):
"""Rewrites urls which actually redirect somewhere else."""
def __init__(self):
self.processed = set()
def on_task_start(self):
self.processed = set()
def url_rewritable(self, task, entry):
if not any(entry['url'].startswith(adapter) for adapter in task.requests.adapters):
return False
return entry['url'] not in self.processed
def url_rewrite(self, task, entry):
try:
# Don't accidentally go online in unit tests
if task.manager.unit_test:
return
r = task.requests.head(entry['url'])
if 300 <= r.status_code < 400 and 'location' in r.headers:
entry['url'] = r.headers['location']
except Exception:
pass
finally:
# Make sure we don't try to rewrite this url again
self.processed.add(entry['url'])
@event('plugin.register')
def register_plugin():
plugin.register(UrlRewriteRedirect, 'urlrewrite_redirect', groups=['urlrewriter'], api_ver=2)
|
Python
| 0 |
@@ -783,16 +783,243 @@
return%0A
+ auth = None%0A if 'download_auth' in entry:%0A auth = entry%5B'download_auth'%5D%0A log.debug('Custom auth enabled for %25s url_redirect: %25s' %25 (entry%5B'title'%5D, entry%5B'download_auth'%5D))%0A
@@ -1057,16 +1057,27 @@
y%5B'url'%5D
+, auth=auth
)%0A
|
e4ca040124e26b06a11e7fb51c3622a213285d24
|
Create thresholding.py
|
thresholding.py
|
thresholding.py
|
Python
| 0 |
@@ -0,0 +1,974 @@
+import numpy as np%0Afrom PIL import Image%0A%0Adef discretize(a):%0A return np.uint8((a %3E 50)*255)%0A%0Aimage_id = 101%0Adirty_image_path = %22../input/train/%25d.png%22 %25 image_id%0Aclean_image_path = %22../input/train_cleaned/%25d.png%22 %25 image_id%0A%0Adirty = Image.open(dirty_image_path)%0Aclean = Image.open(clean_image_path)%0A%0Adirty.save(%22dirty.png%22)%0Aclean.save(%22clean.png%22)%0A%0Aclean_array = np.asarray(clean)%0Adirty_array = np.asarray(dirty)%0A %0Adiscretized_array = discretize(dirty_array)%0AImage.fromarray(discretized_array).save(%22discretized.png%22)%0A%0Ahtml = %22%22%22%3Chtml%3E%0A%09%3Cbody%3E%0A%09%3Ch1%3EThresholding%3C/h1%3E%0A%09%3Cp%3EThis is a very simple attempt to clean up an image by thresholding the pixel value at 50. (Under 50 goes to 0, above 50 goes to 255.)%3C/p%3E%0A%09%3Ch2%3EDirty image%3C/h2%3E%0A%09%3Cimg src=%22dirty.png%22%3E%0A%09%3Ch2%3ECleaned up by thresholding%3C/h2%3E%0A%09%3Cimg src=%22discretized.png%22%3E%0A%09%3Ch2%3EOriginal clean image%3C/h2%3E%0A%09%3Cimg src=%22clean.png%22%3E%0A%09%3C/body%3E%0A%09%3C/html%3E%0A%22%22%22%0A%0Awith open(%22output.html%22, %22w%22) as output_file:%0A%09output_file.write(html)%0A
|
|
d78444cdb6018e2fe49905638ce7645e8de5738b
|
add util/csv_melt.py
|
util/csv_melt.py
|
util/csv_melt.py
|
Python
| 0.000008 |
@@ -0,0 +1,2492 @@
+#!/usr/bin/env python%0A# https://github.com/shenwei356/bio_scripts%22%0Aimport argparse%0Aimport csv%0Aimport re%0Aimport sys%0Aimport pandas as pd%0A%0Aparser = argparse.ArgumentParser(%0A description=%22Melt CSV file, you can append new column%22,%0A epilog=%22https://github.com/shenwei356/bio_scripts%22)%0Aparser.add_argument(%0A 'key',%0A type=str,%0A help=%0A 'Column name of key in csvfile. Multiple values shoud be separated by comma')%0Aparser.add_argument('csvfile', type=str, help='CSV file with head row!')%0Aparser.add_argument('--var_name',%0A type=str,%0A default='var_name',%0A help='name to use for the %22variable%22 column')%0Aparser.add_argument('--value_name',%0A type=str,%0A default='value_name',%0A help='name to use for the %22value%22 column')%0Aparser.add_argument('-a',%0A '--append',%0A type=str,%0A help='another column. format: column=value')%0Aparser.add_argument('-o', '--outfile', type=str, help='output file')%0A%0Aparser.add_argument('--fs', type=str, default=%22,%22, help='field separator %5B,%5D')%0Aparser.add_argument('--fs-out',%0A type=str,%0A help='field separator of ouput %5Bsame as --fs%5D')%0Aparser.add_argument('--qc', type=str, default='%22', help='Quote char%5B%22%5D')%0Aparser.add_argument('-t',%0A action='store_true',%0A help='field separator is %22%5C%5Ct%22. Quote char is %22%5C%5Ct%22')%0A%0Aargs = parser.parse_args()%0A%0Aif args.t:%0A args.fs, args.qc = '%5Ct', '%5Ct'%0Aif not args.fs_out:%0A args.fs_out = args.fs%0A%0Apattern = '%5E(%5B%5E=%5D+)=(%5B%5E=%5D+)$'%0Aif args.append:%0A if not re.search(pattern, args.append):%0A sys.stderr.write(%22bad format for option -a: %7B%7D%22.format(args.append))%0A sys.exit(1)%0A colname, colvalue = re.findall(pattern, args.append)%5B0%5D))%0A%0Akeys = list()%0Aif ',' in args.key:%0A keys = %5Bk for k in args.key.split(',')%5D%0Aelse:%0A keys = %5Bargs.key%5D%0A%0A# ------------------------------------------------------------%0A%0Adf = pd.read_csv(args.csvfile,%0A sep=args.fs,%0A quotechar=args.qc) # , index_col=keys)%0Adf = pd.melt(df,%0A id_vars=keys,%0A var_name=args.var_name,%0A value_name=args.value_name)%0Aif args.append:%0A df%5Bcolname%5D = pd.Series(%5Bcolvalue%5D * len(df))%0A%0Aif args.outfile:%0A df.to_csv(args.outfile, sep=args.fs, quotechar=args.qc, index=0)%0Aelse:%0A df.to_csv(sys.stdout, sep=args.fs, quotechar=args.qc, index=0)%0A
|
|
377c61203d2e684b9b8e113eb120213e85c4487f
|
Fix call to super() (#19279)
|
homeassistant/components/light/lutron.py
|
homeassistant/components/light/lutron.py
|
"""
Support for Lutron lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.lutron/
"""
import logging
from homeassistant.components.light import (
ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light)
from homeassistant.components.lutron import (
LutronDevice, LUTRON_DEVICES, LUTRON_CONTROLLER)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['lutron']
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Lutron lights."""
devs = []
for (area_name, device) in hass.data[LUTRON_DEVICES]['light']:
dev = LutronLight(area_name, device, hass.data[LUTRON_CONTROLLER])
devs.append(dev)
add_entities(devs, True)
def to_lutron_level(level):
"""Convert the given HASS light level (0-255) to Lutron (0.0-100.0)."""
return float((level * 100) / 255)
def to_hass_level(level):
"""Convert the given Lutron (0.0-100.0) light level to HASS (0-255)."""
return int((level * 255) / 100)
class LutronLight(LutronDevice, Light):
"""Representation of a Lutron Light, including dimmable."""
def __init__(self, area_name, lutron_device, controller):
"""Initialize the light."""
self._prev_brightness = None
super().__init__(self, area_name, lutron_device, controller)
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_BRIGHTNESS
@property
def brightness(self):
"""Return the brightness of the light."""
new_brightness = to_hass_level(self._lutron_device.last_level())
if new_brightness != 0:
self._prev_brightness = new_brightness
return new_brightness
def turn_on(self, **kwargs):
"""Turn the light on."""
if ATTR_BRIGHTNESS in kwargs and self._lutron_device.is_dimmable:
brightness = kwargs[ATTR_BRIGHTNESS]
elif self._prev_brightness == 0:
brightness = 255 / 2
else:
brightness = self._prev_brightness
self._prev_brightness = brightness
self._lutron_device.level = to_lutron_level(brightness)
def turn_off(self, **kwargs):
"""Turn the light off."""
self._lutron_device.level = 0
@property
def device_state_attributes(self):
"""Return the state attributes."""
attr = {}
attr['lutron_integration_id'] = self._lutron_device.id
return attr
@property
def is_on(self):
"""Return true if device is on."""
return self._lutron_device.last_level() > 0
def update(self):
"""Call when forcing a refresh of the device."""
if self._prev_brightness is None:
self._prev_brightness = to_hass_level(self._lutron_device.level)
|
Python
| 0 |
@@ -1290,38 +1290,32 @@
uper().__init__(
-self,
area_name, lutro
@@ -2391,23 +2391,8 @@
= %7B
-%7D%0A attr%5B
'lut
@@ -2414,11 +2414,9 @@
_id'
-%5D =
+:
sel
@@ -2434,16 +2434,17 @@
evice.id
+%7D
%0A
|
0b1fc2eb8dad6e5b41e80c5b0d97b9f8a20f9afa
|
Add utils.py
|
krcurrency/utils.py
|
krcurrency/utils.py
|
Python
| 0.000004 |
@@ -0,0 +1,480 @@
+%22%22%22:mod:%60krcurrency.utils%60 --- Helpers%0A~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%0A%0A%22%22%22%0Afrom bs4 import BeautifulSoup as BS%0Aimport requests%0A%0A__all__ = 'request',%0A%0Adef request(url, encoding='utf-8', parselib='lxml'):%0A %22%22%22url%EB%A1%9C %EC%9A%94%EC%B2%AD%ED%95%9C %ED%9B%84 %EB%8F%8C%EB%A0%A4%EB%B0%9B%EC%9D%80 %EA%B0%92%EC%9D%84 BeautifulSoup %EA%B0%9D%EC%B2%B4%EB%A1%9C %EB%B3%80%ED%99%98%ED%95%B4%EC%84%9C %EB%B0%98%ED%99%98%ED%95%A9%EB%8B%88%EB%8B%A4.%0A%0A%0A %22%22%22%0A r = requests.get(url)%0A if r.status_code != 200:%0A return None%0A soup = None%0A try:%0A soup = BeautifulSoup(r.text, parselib)%0A except Exception as e:%0A pass%0A return soup%0A
|
|
76a2c80b015228dd4c6aa932ca9b2faece23a714
|
Create multiplesof3and5.py
|
multiplesof3and5.py
|
multiplesof3and5.py
|
Python
| 0.998635 |
@@ -0,0 +1,311 @@
+#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. %0A#The sum of these multiples is 23.%0A#Find the sum of all the multiples of 3 or 5 below 1000.%0A%0Aanswer = 0%0A%0Afor i in range (1,1000);%0A if i%253 = 0 or i%255 = 0;%0A answer = answer + i%0A else;%0A continue%0Aprint answer%0A
|
|
2d1624f088431e5f71214988499f732695a82b16
|
Bump version 0.15.0rc3 --> 0.15.0rc4
|
lbrynet/__init__.py
|
lbrynet/__init__.py
|
import logging
__version__ = "0.15.0rc3"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
Python
| 0 |
@@ -36,9 +36,9 @@
.0rc
-3
+4
%22%0Ave
|
5dd4deba3d5a53406e735aadad5ac917919b3852
|
add tests for PlotableObject
|
tests/unit/TestPlotableObject.py
|
tests/unit/TestPlotableObject.py
|
Python
| 0 |
@@ -0,0 +1,2155 @@
+import os%0Aimport unittest%0A%0Aimport ROOT%0Afrom PyAnalysisTools.PlottingUtils import PlotableObject as po%0A%0Acwd = os.path.dirname(__file__)%0AROOT.gROOT.SetBatch(True)%0A%0A%0Aclass TestPlotableObject(unittest.TestCase):%0A def test_ctor(self):%0A obj = po.PlotableObject()%0A self.assertIsNone(obj.plot_object)%0A self.assertTrue(obj.is_ref)%0A self.assertEqual(-1, obj.ref_id)%0A self.assertEqual('', obj.label)%0A self.assertIsNone(obj.cuts)%0A self.assertIsNone(obj.process)%0A self.assertEqual('Marker', obj.draw_option)%0A self.assertEqual('Marker', obj.draw)%0A self.assertEqual(1, obj.marker_color)%0A self.assertEqual(1, obj.marker_size)%0A self.assertEqual(1, obj.marker_style)%0A self.assertEqual(1, obj.line_color)%0A self.assertEqual(1, obj.line_width)%0A self.assertEqual(1, obj.line_style)%0A self.assertEqual(0, obj.fill_color)%0A self.assertEqual(0, obj.fill_style)%0A%0A def tests_palettes(self):%0A color_palette = %5BROOT.kGray + 3, ROOT.kRed + 2, ROOT.kAzure + 4, ROOT.kSpring - 6, ROOT.kOrange - 3,%0A ROOT.kCyan - 3, ROOT.kPink - 2, ROOT.kSpring - 9, ROOT.kMagenta - 5%5D%0A marker_style_palette_filled = %5B20, 22, 23, 33, 34, 29, 2%5D%0A marker_style_palette_empty = %5B24, 26, 32, 27, 28, 30, 5%5D%0A line_style_palette_homogen = %5B1, 1, 1, 1, 1%5D%0A line_style_palette_heterogen = %5B1, 1, 4, 8, 6%5D%0A fill_style_palette_left = %5B3305, 3315, 3325, 3335, 3345, 3365, 3375, 3385%5D%0A fill_style_palette_right = %5B3359, 3351, 3352, 3353, 3354, 3356, 3357, 3358%5D%0A%0A self.assertEqual(color_palette, po.color_palette)%0A self.assertEqual(marker_style_palette_filled, po.marker_style_palette_filled)%0A self.assertEqual(marker_style_palette_empty, po.marker_style_palette_empty)%0A self.assertEqual(line_style_palette_homogen, po.line_style_palette_homogen)%0A self.assertEqual(line_style_palette_heterogen, po.line_style_palette_heterogen)%0A self.assertEqual(fill_style_palette_left, po.fill_style_palette_left)%0A self.assertEqual(fill_style_palette_right, po.fill_style_palette_right)%0A
|
|
f0651b2b68ecb4ac093a07d72722b65ea134baa9
|
Remove trailing slashes.
|
pelican/__init__.py
|
pelican/__init__.py
|
import argparse
import os
from pelican.settings import read_settings
from pelican.utils import clean_output_dir
from pelican.writers import Writer
from pelican.generators import (ArticlesGenerator, PagesGenerator,
StaticGenerator, PdfGenerator)
def init_params(settings=None, path=None, theme=None, output_path=None,
markup=None, keep=False):
"""Read the settings, and performs some checks on the environment
before doing anything else.
"""
if settings is None:
settings = {}
settings = read_settings(settings)
path = path or settings['PATH']
if path.endswith('/'):
path = path[:-1]
# define the default settings
theme = theme or settings['THEME']
output_path = output_path or settings['OUTPUT_PATH']
output_path = os.path.realpath(output_path)
markup = markup or settings['MARKUP']
keep = keep or settings['KEEP_OUTPUT_DIRECTORY']
# find the theme in pelican.theme if the given one does not exists
if not os.path.exists(theme):
theme_path = os.sep.join([os.path.dirname(
os.path.abspath(__file__)), "themes/%s" % theme])
if os.path.exists(theme_path):
theme = theme_path
else:
raise Exception("Impossible to find the theme %s" % theme)
if 'SITEURL' not in settings:
settings['SITEURL'] = output_path
# get the list of files to parse
if not path:
raise Exception('you need to specify a path to search the docs on !')
return settings, path, theme, output_path, markup, keep
def run_generators(generators, settings, path, theme, output_path, markup, keep):
"""Run the generators and return"""
context = settings.copy()
generators = [p(context, settings, path, theme, output_path, markup, keep)
for p in generators]
for p in generators:
if hasattr(p, 'generate_context'):
p.generate_context()
# erase the directory if it is not the source
if output_path not in os.path.realpath(path) and not keep:
clean_output_dir(output_path)
writer = Writer(output_path)
for p in generators:
if hasattr(p, 'generate_output'):
p.generate_output(writer)
def run_pelican(settings, path, theme, output_path, markup, delete):
"""Run pelican with the given parameters"""
params = init_params(settings, path, theme, output_path, markup, delete)
generators = [ArticlesGenerator, PagesGenerator, StaticGenerator]
if params[0]['PDF_GENERATOR']: # param[0] is settings
processors.append(PdfGenerator)
run_generators(generators, *params)
def main():
parser = argparse.ArgumentParser(description="""A tool to generate a
static blog, with restructured text input files.""")
parser.add_argument(dest='path',
help='Path where to find the content files')
parser.add_argument('-t', '--theme-path', dest='theme',
help='Path where to find the theme templates. If not specified, it will'
'use the default one included with pelican.')
parser.add_argument('-o', '--output', dest='output',
help='Where to output the generated files. If not specified, a directory'
' will be created, named "output" in the current path.')
parser.add_argument('-m', '--markup', default='', dest='markup',
help='the markup language to use (rst or md).')
parser.add_argument('-s', '--settings', dest='settings',
help='the settings of the application. Default to None.')
parser.add_argument('-k', '--keep-output-directory', dest='keep', action='store_true',
help='Keep the output directory and just update all the generated files. Default is to delete the output directory.')
args = parser.parse_args()
markup = [a.strip().lower() for a in args.markup.split(',')]
run_pelican(args.settings, args.path, args.theme, args.output, markup, args.keep)
if __name__ == '__main__':
main()
|
Python
| 0.000005 |
@@ -207,17 +207,16 @@
nerator,
-
%0A
@@ -344,17 +344,16 @@
th=None,
-
%0A
@@ -1815,17 +1815,16 @@
p, keep)
-
%0A
|
854a1ab7c13b4d4d8e28ab13f0cdaef5c1fcb9a6
|
Create solution.py
|
hackerrank/algorithms/warmup/easy/compare_the_triplets/py/solution.py
|
hackerrank/algorithms/warmup/easy/compare_the_triplets/py/solution.py
|
Python
| 0.000018 |
@@ -0,0 +1,413 @@
+#!/bin/python3%0A%0Aimport sys%0A%0Acmp = lambda a, b: (a %3E b) - (b %3E a)%0A%0AaliceScores = tuple(map(int, input().strip().split(' ')))%0AbobScores = tuple(map(int, input().strip().split(' ')))%0A%0AscoreCmp = tuple(map(lambda a, b: cmp(a, b), aliceScores, bobScores))%0AaliceScore = len(tuple(filter(lambda x: x %3E 0, scoreCmp)))%0AbobScore = len(tuple(filter(lambda x: x %3C 0, scoreCmp)))%0A%0Aprint(aliceScore, bobScore)%0A
|
|
4764b5248cf91042a12ce6aef77a04c37360eb4f
|
Add initial shell of Pyglab class.
|
pyglab/pyglab.py
|
pyglab/pyglab.py
|
Python
| 0 |
@@ -0,0 +1,365 @@
+import requests%0A%0A%0Aclass Pyglab(object):%0A def __init__(self, token):%0A self.token = token%0A self.headers = %7B'PRIVATE-TOKEN', token%7D%0A self.user = None%0A%0A def sudo(self, user):%0A %22%22%22Permanently set a different username. Returns the old username.%22%22%22%0A%0A previous_user = self.user%0A self.user = user%0A return previous_user%0A
|
|
70e04b20c5d78b41546aa4ea1a1e2fd82af7527f
|
Add JSON HttpResponse that does the encoding for you.
|
comrade/http/__init__.py
|
comrade/http/__init__.py
|
Python
| 0 |
@@ -0,0 +1,573 @@
+from django.core.serializers import json, serialize%0Afrom django.db.models.query import QuerySet%0Afrom django.http import HttpResponse%0Afrom django.utils import simplejson%0A%0Aclass HttpJsonResponse(HttpResponse):%0A def __init__(self, object, status=None):%0A if isinstance(object, QuerySet):%0A content = serialize('json', object)%0A else:%0A content = simplejson.dumps(object, cls=json.DjangoJSONEncoder,%0A ensure_ascii=False)%0A super(HttpJsonResponse, self).__init__(%0A content, content_type='application/json')%0A
|
|
d3ba2b8cf84ba54d932fcc48b464f125798c0b27
|
Add simple bash with git install script
|
toolbox/install_script_git.sh.py
|
toolbox/install_script_git.sh.py
|
Python
| 0 |
@@ -0,0 +1,587 @@
+#!/bin/bash%0Avenv=%22nephoria_venv%22%0Aneph_branch=%22oldboto%22%0Aadminapi_branch=%22master%22%0Ayum install -y python-devel gcc git python-setuptools python-virtualenv%0Aif %5B ! -d adminapi %5D; then%0A git clone https://github.com/nephomaniac/adminapi.git%0Afi%0Aif %5B ! -d nephoria %5D; then%0A git clone https://github.com/nephomaniac/nephoria.git%0Afi%0Aif %5B %22x$venv%22 != %22x%22 %5D; then%0A if %5B ! -d $venv %5D; then%0A virtualenv $venv%0A fi%0A source $venv/bin/activate%0Afi%0Acd adminapi%0Agit checkout $adminapi_branch%0Apython setup.py install%0Acd -%0Acd nephoria%0Agit checkout $neph_branch%0Apython setup.py install%0Acd -
|
|
5ae194cacef0a24c3d6a0714d3f435939973b3cb
|
Add some helpful utilities
|
utils.py
|
utils.py
|
Python
| 0 |
@@ -0,0 +1,478 @@
+from functools import wraps%0A%0A%0Adef cached_property(f):%0A name = f.__name__%0A @property%0A @wraps(f)%0A def inner(self):%0A if not hasattr(self, %22_property_cache%22):%0A self._property_cache = %7B%7D%0A if name not in self._property_cache:%0A self._property_cache%5Bname%5D = f(self)%0A return self._property_cache%5Bname%5D%0A return inner%0A%0A%0Aclass Constant():%0A def __init__(self, x):%0A self.x = x%0A%0A def __repr__(self):%0A return self.x%0A
|
|
93b1253389075174fa942e848d6c1f7666ffc906
|
add solution for Combination Sum II
|
src/combinationSumII.py
|
src/combinationSumII.py
|
Python
| 0.000001 |
@@ -0,0 +1,704 @@
+class Solution:%0A # @param candidates, a list of integers%0A # @param target, integer%0A # @return a list of lists of integers%0A%0A def combinationSum2(self, candidates, target):%0A if not candidates:%0A return %5B%5D%0A candidates.sort()%0A n = len(candidates)%0A res = set()%0A%0A def solve(start, target, tmp):%0A if target %3C 0:%0A return%0A if target == 0:%0A res.add(tuple(tmp))%0A return%0A for i in xrange(start, n):%0A tmp.append(candidates%5Bi%5D)%0A solve(i+1, target-candidates%5Bi%5D, tmp)%0A tmp.pop()%0A%0A solve(0, target, %5B%5D)%0A return map(list, res)%0A
|
|
19d5b2f58d712f49638dad83996f9e60a6ebc949
|
Add a release script.
|
release.py
|
release.py
|
Python
| 0 |
@@ -0,0 +1,837 @@
+#!/usr/bin/env python%0Aimport re%0Aimport ast%0Aimport subprocess%0A%0Adef version():%0A _version_re = re.compile(r'__version__%5Cs+=%5Cs+(.*)')%0A%0A with open('pgcli/__init__.py', 'rb') as f:%0A version = str(ast.literal_eval(_version_re.search(%0A f.read().decode('utf-8')).group(1)))%0A%0A return version%0A%0Adef create_git_tag(tag_name):%0A cmd = %5B'git', 'tag', tag_name%5D%0A print ' '.join(cmd)%0A subprocess.check_output(cmd)%0A%0Adef register_with_pypi():%0A cmd = %5B'python', 'setup.py', 'register'%5D%0A print ' '.join(cmd)%0A subprocess.check_output(cmd)%0A%0Adef create_source_tarball():%0A cmd = %5B'python', 'setup.py', 'sdist'%5D%0A print ' '.join(cmd)%0A subprocess.check_output(cmd)%0A%0Aif __name__ == '__main__':%0A ver = version()%0A print ver%0A create_git_tag('v%25s' %25 ver)%0A register_with_pypi()%0A create_source_tarball()%0A
|
|
7d2906d58db373f5f7326c140e8cb191bc3d0059
|
Make other logging work when logging/config_file is in use
|
mopidy/utils/log.py
|
mopidy/utils/log.py
|
from __future__ import unicode_literals
import logging
import logging.config
import logging.handlers
class DelayedHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
self._released = False
self._buffer = []
def handle(self, record):
if not self._released:
self._buffer.append(record)
def release(self):
self._released = True
root = logging.getLogger('')
while self._buffer:
root.handle(self._buffer.pop(0))
_delayed_handler = DelayedHandler()
def bootstrap_delayed_logging():
root = logging.getLogger('')
root.setLevel(logging.NOTSET)
root.addHandler(_delayed_handler)
def setup_logging(config, verbosity_level, save_debug_log):
logging.captureWarnings(True)
setup_log_levels(config)
setup_console_logging(config, verbosity_level)
if save_debug_log:
setup_debug_logging_to_file(config)
if config['logging']['config_file']:
logging.config.fileConfig(config['logging']['config_file'])
_delayed_handler.release()
def setup_log_levels(config):
for name, level in config['loglevels'].items():
logging.getLogger(name).setLevel(level)
LOG_LEVELS = {
-1: dict(root=logging.ERROR, mopidy=logging.WARNING),
0: dict(root=logging.ERROR, mopidy=logging.INFO),
1: dict(root=logging.WARNING, mopidy=logging.DEBUG),
2: dict(root=logging.INFO, mopidy=logging.DEBUG),
3: dict(root=logging.DEBUG, mopidy=logging.DEBUG),
}
class VerbosityFilter(logging.Filter):
def __init__(self, verbosity_level):
self.verbosity_level = verbosity_level
def filter(self, record):
if record.name.startswith('mopidy'):
required_log_level = LOG_LEVELS[self.verbosity_level]['mopidy']
else:
required_log_level = LOG_LEVELS[self.verbosity_level]['root']
return record.levelno >= required_log_level
def setup_console_logging(config, verbosity_level):
if verbosity_level < min(LOG_LEVELS.keys()):
verbosity_level = min(LOG_LEVELS.keys())
if verbosity_level > max(LOG_LEVELS.keys()):
verbosity_level = max(LOG_LEVELS.keys())
verbosity_filter = VerbosityFilter(verbosity_level)
if verbosity_level < 1:
log_format = config['logging']['console_format']
else:
log_format = config['logging']['debug_format']
formatter = logging.Formatter(log_format)
handler = logging.StreamHandler()
handler.addFilter(verbosity_filter)
handler.setFormatter(formatter)
logging.getLogger('').addHandler(handler)
def setup_debug_logging_to_file(config):
formatter = logging.Formatter(config['logging']['debug_format'])
handler = logging.handlers.RotatingFileHandler(
config['logging']['debug_file'], maxBytes=10485760, backupCount=3)
handler.setFormatter(formatter)
logging.getLogger('').addHandler(handler)
|
Python
| 0 |
@@ -797,16 +797,265 @@
(True)%0A%0A
+ if config%5B'logging'%5D%5B'config_file'%5D:%0A # Logging config from file must be read before other handlers are%0A # added. If not, the other handlers will have no effect.%0A logging.config.fileConfig(config%5B'logging'%5D%5B'config_file'%5D)%0A%0A
setu
@@ -1198,118 +1198,8 @@
g)%0A%0A
- if config%5B'logging'%5D%5B'config_file'%5D:%0A logging.config.fileConfig(config%5B'logging'%5D%5B'config_file'%5D)%0A%0A
|
0003b3fe31a1b92dda994b2f7eacf6cef7e08ce4
|
Add check_blocked.py
|
check_blocked.py
|
check_blocked.py
|
Python
| 0.000002 |
@@ -0,0 +1,2613 @@
+# This script is licensed under the GNU Affero General Public License%0A# either version 3 of the License, or (at your option) any later%0A# version.%0A#%0A# This script was tested on GNU/Linux opreating system.%0A#%0A# To run this script:%0A# 1) Download the list of articles for the Wikipedia edition that%0A# you want to scan from http://download.wikimedia.org.%0A# 2) Using 'split' command, split th article list into peices. This%0A# will result in files that start with 'x' eg. 'xaa', xab', etc.%0A# 3) If you are working on a Wikipedia edition that's different from%0A# the Arabic one, change self.lang_code into the code of your%0A# edition.%0A# 4) Run the script from the directory of the split files.%0A%0Aimport urllib2%0Aimport time%0Aimport os%0Aimport codecs%0Aimport shelve%0A%0Aclass checkBlocked:%0A def __init__(self):%0A self.lang_code = 'ar'%0A self.list_directory = os.getcwd()%0A self.list_files = %5Bi for i in os.listdir('.') if i.startswith('x')%5D%0A self.list_files.sort()%0A%0A def fetch_list(self, next_list, old_list):%0A if old_list is not None:%0A print %22Removing list%22, old_list%0A os.remove(self.list_directory+'/'+old_list)%0A%0A list_lines = codecs.open(self.list_directory+'/'+next_list, 'r', encoding=%22utf-8%22).readlines()%0A list_items = %5Bi.strip() for i in list_lines%5D%0A%0A return list_items%0A %0A def is_blocked(self, list_item):%0A url = %22http://%25s.wikipedia.org/wiki/%22 %25 self.lang_code + urllib2.quote(list_item.encode('utf8'))%0A print url%0A%0A while True:%0A try:%0A urllib2.urlopen(url)%0A except urllib2.HTTPError:%0A print list_item, %22isn't blocked.%22%0A return False%0A except urllib2.URLError:%0A print %22Error, retrying...%22%0A time.sleep(1)%0A continue%0A%0A print list_item, %22is blocked.%22%0A return True%0A%0A def run(self):%0A old_list = None%0A try:%0A for list_file in self.list_files:%0A database = shelve.open(%22check_blocked.db%22)%0A list_items = self.fetch_list(list_file, old_list)%0A for list_item in list_items:%0A if self.is_blocked(list_item):%0A datebase_key = str(len(database))%0A datebase%5Bdatebase_key%5D = list_item%0A old_list = list_file%0A database.close() %0A except KeyboardInterrupt:%0A print %22Existing...%22%0A database.close()%0A%0A%0Aif __name__ == '__main__':%0A bot = checkBlocked()%0A bot.run()%0A
|
|
9b3e0c7eb28a67e2383cad6cbfa97fc4fd575756
|
Add error classification
|
classify_logs.py
|
classify_logs.py
|
Python
| 0.000002 |
@@ -0,0 +1,1387 @@
+import re%0Aimport yaml%0A%0Aerror_types = %5B%22no package found%22,%0A %22unclassified%22%5D%0A%0A%0Adef classify_build_log(log_file):%0A %22%22%22%0A Takes a build log file object as an input and returns%0A a tupe %60(category, sub-category, sub-category)%60%0A%0A - missing dependency:%0A - Build Dependency%0A - Test Dependency%0A - Runtime error (other than missing dependency)%0A %22%22%22%0A log = log_file.readlines()%0A if no_packages_found(log):%0A return %22no package found%22%0A if has_missing_test_dependency(log):%0A return %22missing test dependency%22%0A%0A return %22unclassified%22%0A pass%0A%0A%0Adef has_missing_test_dependency(log):%0A %22%22%22%0A Return: (Status, missing packages)%0A %22%22%22%0A None%0A%0A%0Adef no_packages_found(log):%0A p = re.compile(r%22Error: No packages found%22)%0A return any(%5Bre.match(p, line) for line in log%5D)%0A%0A%0Adef classify_all_logs():%0A packages = yaml.load(file('packages.yaml', 'r'))%0A log_dir = %22./logs/%22%0A%0A for package in packages:%0A if package%5B'build'%5D is False:%0A log_file_name = log_dir + %22%25s_build.log%22 %25 (package%5B'name'%5D)%0A log_file = open(log_file_name, 'r')%0A error_type = classify_build_log(log_file)%0A else:%0A error_type = None%0A package%5B'build_error_type'%5D = error_type%0A open('packages.yaml', 'w').writelines(yaml.dump(packages))%0A%0A%0Aif __name__ == %22__main__%22:%0A classify_all_logs()%0A
|
|
aafa99714eff3c5021594ae5021bdd47b41c9c6b
|
save tpl environs after invoke shell constructor
|
assets/save_tpl_envs.py
|
assets/save_tpl_envs.py
|
Python
| 0 |
@@ -0,0 +1,352 @@
+# -*- coding:utf-8 -*-%0A%0Aimport os%0Aimport sys%0Aimport json%0A%0A%0Adef save_tpl_envs(path):%0A envs = %7B%7D%0A for key, value in os.environ.items():%0A if key.startswith('TPL_'):%0A envs%5Bkey%5B4:%5D%5D = value%0A with open(path, 'w') as fd:%0A fd.write(json.dumps(envs))%0A%0A%0Aif __name__ == '__main__':%0A path = sys.argv%5B1%5D%0A save_tpl_envs(path)%0A
|
|
af9b0ee39d18ca174b19143bdda0d478c4d5a834
|
add a driver for hourly reporting
|
scripts/iemre/rerun_hourly.py
|
scripts/iemre/rerun_hourly.py
|
Python
| 0 |
@@ -0,0 +1,255 @@
+import mx.DateTime%0Aimport stage4_hourlyre%0A%0Asts = mx.DateTime.DateTime(2010,5,1)%0Aets = mx.DateTime.DateTime(2010,5,13)%0Ainterval = mx.DateTime.RelativeDateTime(hours=1)%0Anow = sts%0Awhile now %3C ets:%0A print now%0A stage4_hourlyre.merge( now )%0A now += interval%0A
|
|
0920a23a72e1e14179b75b4d2a50e956ee9deec0
|
add skeleton generation file
|
disaggregator/generate.py
|
disaggregator/generate.py
|
Python
| 0.000005 |
@@ -0,0 +1,163 @@
+from appliance import ApplianceTrace%0Afrom appliance import ApplianceInstance%0Afrom appliance import ApplianceSet%0Afrom appliance import ApplianceType%0A%0Aimport fhmm%0A%0A%0A
|
|
8ccab210054c2776a36b7e3648fa1e27eb49a27b
|
add deeplearning cross-validation NOPASS. PUBDEV-1696.
|
h2o-py/tests/testdir_algos/deeplearning/pyunit_NOPASS_cv_carsDeepLearning.py
|
h2o-py/tests/testdir_algos/deeplearning/pyunit_NOPASS_cv_carsDeepLearning.py
|
Python
| 0 |
@@ -0,0 +1,2302 @@
+import sys%0Asys.path.insert(1, %22../../../%22)%0Aimport h2o%0Aimport random%0A%0Adef cv_carsDL(ip,port):%0A # Connect to h2o%0A h2o.init(ip,port)%0A%0A # read in the dataset and construct training set (and validation set)%0A cars = h2o.import_frame(path=h2o.locate(%22smalldata/junit/cars_20mpg.csv%22))%0A%0A # choose the type model-building exercise (multinomial classification or regression). 0:regression, 1:binomial,%0A # 2:multinomial%0A problem = random.sample(range(3),1)%5B0%5D%0A%0A # pick the predictors and the correct response column%0A predictors = %5B%22displacement%22,%22power%22,%22weight%22,%22acceleration%22,%22year%22%5D%0A if problem == 1 :%0A response_col = %22economy_20mpg%22%0A cars%5Bresponse_col%5D = cars%5Bresponse_col%5D.asfactor()%0A elif problem == 2 :%0A response_col = %22cylinders%22%0A cars%5Bresponse_col%5D = cars%5Bresponse_col%5D.asfactor()%0A else :%0A response_col = %22economy%22%0A%0A print %22Response column: %7B0%7D%22.format(response_col)%0A%0A ## cross-validation%0A ## basic%0A nfolds = random.randint(3,10)%0A dl = h2o.deeplearning(y=cars%5Bresponse_col%5D, x=cars%5Bpredictors%5D, nfolds=nfolds)%0A%0A ## boundary case%0A # nfolds = 0%0A dl = h2o.deeplearning(y=cars%5Bresponse_col%5D, x=cars%5Bpredictors%5D, nfolds=0)%0A%0A ## error cases%0A # 1. nfolds == 1 or %3C 0%0A # TODO: PUBDEV-1696%0A try:%0A dl = h2o.deeplearning(y=cars%5Bresponse_col%5D, x=cars%5Bpredictors%5D, nfolds=random.randint(-10000,-1))%0A dl = h2o.deeplearning(y=cars%5Bresponse_col%5D, x=cars%5Bpredictors%5D, nfolds=1)%0A assert False, %22Expected model-build to fail when nfolds is 1 or %3C 0%22%0A except EnvironmentError:%0A assert True%0A%0A # 2. cross-validation and regular validation attempted%0A r = cars%5B0%5D.runif()%0A train = cars%5Br %3E .2%5D%0A valid = cars%5Br %3C= .2%5D%0A try:%0A dl = h2o.deeplearning(y=train%5Bresponse_col%5D, x=train%5Bpredictors%5D, nfolds=random.randint(3,10),%0A validation_y=valid%5B1%5D, validation_x=valid%5Bpredictors%5D)%0A assert False, %22Expected model-build to fail when both cross-validation and regular validation is attempted%22%0A except EnvironmentError:%0A assert True%0A%0A # TODO: what should the model metrics look like? add cross-validation metric check to pyunit_metric_json_check.%0A%0Aif __name__ == %22__main__%22:%0A h2o.run_test(sys.argv, cv_carsDL)
|
|
85a17f8a483c072192d9d267ca4a8c5e8224cd40
|
assert_not_contains
|
django_nose/assertions.py
|
django_nose/assertions.py
|
# vim: tabstop=4 expandtab autoindent shiftwidth=4 fileencoding=utf-8
"""
Assertions that sort of follow Python unittest/Django test cases
"""
from django.utils.encoding import smart_str
from django.http import QueryDict
from urlparse import urlsplit, urlunsplit
## Python
def fail_unless_equal(first, second, msg=None):
assert first == second, (msg or '%s != %s' % (first, second))
assert_equal = assert_equals = fail_unless_equal
def fail_if_equal(first, second, msg=None):
assert first != second, (msg or '%s == %s' % (first, second))
assert_not_equal = assert_not_equals = fail_if_equal
def fail_unless_almost_equal(first, second, places=7, msg=None):
assert round(abs(second-first), places) != 0, (msg or '%s == %s within %s places' % (first, second, places))
assert_almost_equal = assert_almost_equals = fail_unless_almost_equal
def fail_if_almost_equal(first, second, places=7, msg=None):
assert round(abs(second-first), places) == 0, (msg or '%s != %s within %s places' % (first, second, places))
assert_not_almost_equal = assert_not_almost_equals = fail_if_almost_equal
def fail_unless_raises(exc_class, callable_obj, *args, **kwargs):
try:
callable_obj(*args, **kwargs)
except exc_class:
return
else:
if hasattr(exc_class, '__name__'):
exc_name = exc_class.__name__
else:
exc_name = str(exc_class)
raise AssertionError('%s not raised' % exc_name)
assert_raises = fail_unless_raises
## Django
def assert_contains(response, text, count=None, status_code=200, msg_prefix=''):
if msg_prefix:
msg_prefix = '%s: ' % msg_prefix
assert response.status_code == status_code, msg_prefix + "Couldn't retrieve page: Response code was %d (expeced %d)" % (response.status_code, status_code)
text = smart_str(text, response._charset)
real_count = response.content.count(text)
if count is not None:
assert real_count == count, msg_prefix + "Found %d instances of '%s' in response (expected %d)" % (real_count, text, count)
else:
assert real_count != 0, msg_prefix + "Couldn't find '%s' in response" % text
def assert_not_contains(response, text, status_code=200, msg_prefix=''):
if msg_prefix:
msg_prefix = '%s: ' % msg_prefix
assert False
def assert_form_error(response, form, field, errors, msg_prefix=''):
if msg_prefix:
msg_prefix = '%s: ' % msg_prefix
assert False
def assert_template_used(response, template_name, msg_prefix=''):
if msg_prefix:
msg_prefix = '%s: ' % msg_prefix
assert False
def assert_redirects(response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix=''):
if msg_prefix:
msg_prefix = '%s: ' % msg_prefix
if hasattr(response, 'redirect_chain'):
# The request was a followed redirect
assert len(response.redirect_chain), msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)" % (response.status_code, status_code)
assert response.redirect_chain[0][1] == status_code, msg_prefix + "Initial response didn't redirect as expected: Response code was %d (expected %d)" % (response.redirect_chain[0][1], status_Code)
# 2010-05-24: mjt: is this a bug in Django?
url, status_code = response.redirect_chain[-1]
# 2010-05-24: mjt: Django says response.status_code == but we do not
assert status_code == target_status_code, msg_prefix + "Response didn't redirect as expected: Final Response code was %d (expected %d)" % (status_code, target_status_code)
else:
# Not a followed redirect
assert response.status_code == status_code, msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)" % (response.status_code, status_code)
url = response['Location']
scheme, netloc, path, query, fragment = urlsplit(url)
redirect_response = response.client.get(path, QueryDict(query))
# Get the redirection page, using the same client that was used
# to obtain the original response.
assert redirect_response.status_code == target_status_code, msg_prefix + "Couldn't retrieve redirection page '%s': response code was %d (expected %d)" % (path, redirect_response.status_code, target_status_code)
e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url)
if not (e_scheme or e_netloc):
expected_url = urlunsplit(('http', host or 'testserver', e_path, e_query, e_fragment))
assert url == expected_url, msg_prefix + "Response redirected to '%s, expected '%s'" % (url, expected_url)
# EOF
|
Python
| 0.999999 |
@@ -2290,37 +2290,328 @@
fix%0A%0A assert
-False
+response.status_code == status_code, msg_prefix + %22Couldn't retrieve page: Response code was %25d (expeced %25d)%22 %25 (response.status_code, status_code)%0A%0A text = smart_str(text, response._charset)%0A%0A assert response.content.count(text) == 0, msg_prefix + %22Response should not contain '%25s'%22 %25 text
%0A%0Adef assert_for
|
063a701770d6613e5fdebaa7ae89d4d997c155ad
|
fix XSS in My Graphs
|
webapp/graphite/browser/views.py
|
webapp/graphite/browser/views.py
|
"""Copyright 2008 Orbitz WorldWide
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 re
from django.conf import settings
from django.shortcuts import render_to_response
from django.utils.safestring import mark_safe
from django.utils.html import escape
from graphite.account.models import Profile
from graphite.compat import HttpResponse
from graphite.util import getProfile, getProfileByUsername, json
from graphite.logger import log
from hashlib import md5
def header(request):
"View for the header frame of the browser UI"
context = {}
context['user'] = request.user
context['profile'] = getProfile(request)
context['documentation_url'] = settings.DOCUMENTATION_URL
context['login_url'] = settings.LOGIN_URL
return render_to_response("browserHeader.html", context)
def browser(request):
"View for the top-level frame of the browser UI"
context = {
'queryString': mark_safe(request.GET.urlencode()),
'target': request.GET.get('target')
}
if context['queryString']:
context['queryString'] = context['queryString'].replace('#','%23')
if context['target']:
context['target'] = context['target'].replace('#','%23') #js libs terminate a querystring on #
return render_to_response("browser.html", context)
def search(request):
query = request.POST.get('query')
if not query:
return HttpResponse("")
patterns = query.split()
regexes = [re.compile(p,re.I) for p in patterns]
def matches(s):
for regex in regexes:
if regex.search(s):
return True
return False
results = []
index_file = open(settings.INDEX_FILE)
for line in index_file:
if matches(line):
results.append( line.strip() )
if len(results) >= 100:
break
index_file.close()
result_string = ','.join(results)
return HttpResponse(result_string, content_type='text/plain')
def myGraphLookup(request):
"View for My Graphs navigation"
profile = getProfile(request,allowDefault=False)
assert profile
nodes = []
leafNode = {
'allowChildren' : 0,
'expandable' : 0,
'leaf' : 1,
}
branchNode = {
'allowChildren' : 1,
'expandable' : 1,
'leaf' : 0,
}
try:
path = request.GET.get('path', u'')
if path:
if path.endswith('.'):
userpath_prefix = path
else:
userpath_prefix = path + '.'
else:
userpath_prefix = u""
matches = [ graph for graph in profile.mygraph_set.all().order_by('name') if graph.name.startswith(userpath_prefix) ]
log.info( "myGraphLookup: username=%s, path=%s, userpath_prefix=%s, %ld graph to process" % (profile.user.username, path, userpath_prefix, len(matches)) )
branch_inserted = set()
leaf_inserted = set()
for graph in matches: #Now let's add the matching graph
isBranch = False
dotPos = graph.name.find( '.', len(userpath_prefix) )
if dotPos >= 0:
isBranch = True
name = graph.name[ len(userpath_prefix) : dotPos ]
if name in branch_inserted: continue
branch_inserted.add(name)
else:
name = graph.name[ len(userpath_prefix): ]
if name in leaf_inserted: continue
leaf_inserted.add(name)
node = {'text': name}
if isBranch:
node.update({'id': userpath_prefix + name + '.'})
node.update(branchNode)
else:
m = md5()
m.update(name.encode('utf-8'))
node.update( { 'id' : str(userpath_prefix + m.hexdigest()), 'graphUrl' : str(graph.url) } )
node.update(leafNode)
nodes.append(node)
except:
log.exception("browser.views.myGraphLookup(): could not complete request.")
if not nodes:
no_graphs = { 'text' : "No saved graphs", 'id' : 'no-click' }
no_graphs.update(leafNode)
nodes.append(no_graphs)
return json_response(nodes, request)
def userGraphLookup(request):
"View for User Graphs navigation"
user = request.GET.get('user')
path = request.GET['path']
if user:
username = user
graphPath = path[len(username)+1:]
elif '.' in path:
username, graphPath = path.split('.', 1)
else:
username, graphPath = path, None
nodes = []
branchNode = {
'allowChildren' : 1,
'expandable' : 1,
'leaf' : 0,
}
leafNode = {
'allowChildren' : 0,
'expandable' : 0,
'leaf' : 1,
}
try:
if not username:
profiles = Profile.objects.exclude(user__username='default')
for profile in profiles:
if profile.mygraph_set.count():
node = {
'text' : str(profile.user.username),
'id' : str(profile.user.username)
}
node.update(branchNode)
nodes.append(node)
else:
profile = getProfileByUsername(username)
assert profile, "No profile for username '%s'" % username
if graphPath:
prefix = graphPath.rstrip('.') + '.'
else:
prefix = ''
matches = [ graph for graph in profile.mygraph_set.all().order_by('name') if graph.name.startswith(prefix) ]
inserted = set()
for graph in matches:
relativePath = graph.name[ len(prefix): ]
nodeName = relativePath.split('.')[0]
if nodeName in inserted:
continue
inserted.add(nodeName)
if '.' in relativePath: # branch
node = {
'text' : escape(str(nodeName)),
'id' : str(username + '.' + prefix + nodeName + '.'),
}
node.update(branchNode)
else: # leaf
m = md5()
m.update(nodeName)
node = {
'text' : escape(str(nodeName)),
'id' : str(username + '.' + prefix + m.hexdigest()),
'graphUrl' : str(graph.url),
}
node.update(leafNode)
nodes.append(node)
except:
log.exception("browser.views.userLookup(): could not complete request for %s" % username)
if not nodes:
no_graphs = { 'text' : "No saved graphs", 'id' : 'no-click' }
no_graphs.update(leafNode)
nodes.append(no_graphs)
nodes.sort()
return json_response(nodes, request)
def json_response(nodes, request=None):
if request:
jsonp = request.REQUEST.get('jsonp', False)
else:
jsonp = False
#json = str(nodes) #poor man's json encoder for simple types
json_data = json.dumps(nodes)
if jsonp:
response = HttpResponse("%s(%s)" % (jsonp, json_data),
content_type="text/javascript")
else:
response = HttpResponse(json_data, content_type="application/json")
response['Pragma'] = 'no-cache'
response['Cache-Control'] = 'no-cache'
return response
|
Python
| 0.000002 |
@@ -3673,20 +3673,28 @@
'text':
+escape(
name
+)
%7D%0A%0A
|
1483f6cece70cb5de115ea1edc630e98292a8170
|
Add Sorting/Selection.py & Selection()
|
Sorting/Selection.py
|
Sorting/Selection.py
|
Python
| 0 |
@@ -0,0 +1,1575 @@
+# @auther Besir Kurtulmus%0A# coding: utf-8%0A'''%0AThe MIT License (MIT)%0A%0ACopyright (c) 2014 Ahmet Besir Kurtulmus%0A%0APermission is hereby granted, free of charge, to any person obtaining a copy of%0Athis software and associated documentation files (the %22Software%22), to deal in%0Athe Software without restriction, including without limitation the rights to%0Ause, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of%0Athe Software, and to permit persons to whom the Software is furnished to do so,%0Asubject to the following conditions:%0A%0AThe above copyright notice and this permission notice shall be included in all%0Acopies or substantial portions of the Software.%0A%0ATHE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0AIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS%0AFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR%0ACOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER%0AIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN%0ACONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.%0A'''%0Afrom random import choice%0Afrom MergeSort import RandomList%0A%0Adef Selection(l, k):%0A%09%22%22%22%0A%09Description:%0A%0A%09Args:%0A%0A%09Examples:%0A%09%22%22%22%0A%09v = choice(l)%0A%09sL = %5B%5D%0A%09sR = %5B%5D%0A%09sV = %5B%5D%0A%09for i in l:%0A%09%09if i %3C v:%0A%09%09%09sL.append(i)%0A%09%09elif i == v:%0A%09%09%09sV.append(i)%0A%09%09elif i %3E v:%0A%09%09%09sR.append(i)%0A%09if k %3C= len(sL):%0A%09%09Selection(sL, k)%0A%09elif k %3C= (len(sL) + len(sV)):%0A%09%09return v%0A%09elif k %3E (len(sL) + len(sV)):%0A%09%09Selection(sR, k - len(sL) - len(sV))%0A%09else:%0A%09%09return v%0A
|
|
973696b0c50f235cfcef9e0cb30c6fc2f1028058
|
add an index for the story_storytags table
|
storyboard/db/migration/alembic_migrations/versions/063_index_story_storytags.py
|
storyboard/db/migration/alembic_migrations/versions/063_index_story_storytags.py
|
Python
| 0.000006 |
@@ -0,0 +1,1003 @@
+# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A#%0A%0A%22%22%22index story_storytags%0A%0ARevision ID: a6e048164572%0ARevises: 062%0ACreate Date: 2018-06-25 17:13:43.992561%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '063'%0Adown_revision = '062'%0A%0A%0Afrom alembic import op%0A%0A%0Adef upgrade(active_plugins=None, options=None):%0A op.create_index('story_storytags_idx',%0A 'story_storytags', %5B'story_id'%5D)%0A%0A%0Adef downgrade(active_plugins=None, options=None):%0A op.drop_index('story_storytags_idx')%0A
|
|
3c4fd0477c7d6f9d0f30654271e73466d192d1e1
|
Add data type for vectors
|
drudge/vec.py
|
drudge/vec.py
|
Python
| 0 |
@@ -0,0 +1,2635 @@
+%22%22%22Vectors and utilities.%22%22%22%0A%0Aimport collections.abc%0A%0Afrom sympy import sympify%0A%0A%0Aclass Vec:%0A %22%22%22Vectors.%0A%0A Vectors are the basic non-commutative quantities. Its objects consist of%0A an base and some indices. The base is allowed to be any Python object,%0A although small hashable objects, like string, are advised. The indices%0A are always sympified into SymPy expressions.%0A%0A Its objects can be created directly by giving the base and indices,%0A or existing vector objects can be subscripted to get new ones. The%0A semantics is similar to Haskell functions.%0A%0A Note that users cannot directly assign to the attributes of this class.%0A%0A This class can be used by itself, it can also be subclassed for special%0A use cases.%0A%0A %22%22%22%0A%0A __slots__ = %5B'_base', '_indices'%5D%0A%0A def __init__(self, base, indices=()):%0A %22%22%22Initialize a vector.%0A%0A Atomic indices are added as the only index. Iterable values will%0A have all of its entries added.%0A %22%22%22%0A self._base = base%0A if not isinstance(indices, collections.abc.Iterable):%0A indices = (indices,)%0A self._indices = tuple(sympify(i) for i in indices)%0A%0A @property%0A def base(self):%0A %22%22%22Get the base of the vector.%22%22%22%0A return self._base%0A%0A @property%0A def indices(self):%0A %22%22%22Get the indices of the vector.%22%22%22%0A return self._indices%0A%0A def __getitem__(self, item):%0A %22%22%22Append the given indices to the vector.%0A%0A When multiple new indices are to be given, they have to be given as a%0A tuple.%0A %22%22%22%0A%0A if not isinstance(item, tuple):%0A item = (item,)%0A%0A new_indices = tuple(sympify(i) for i in item)%0A%0A # Pay attention to subclassing.%0A return type(self)(self.base, self.indices + new_indices)%0A%0A def __repr__(self):%0A %22%22%22Form repr string form the vector.%22%22%22%0A return ''.join(%5B%0A type(self).__name__, '(', repr(self.base), ', (',%0A ', '.join(repr(i) for i in self.indices),%0A '))'%0A %5D)%0A%0A def __str__(self):%0A %22%22%22Form a more readable string representation.%22%22%22%0A%0A return ''.join(%5B%0A str(self.base), '%5B', ', '.join(str(i) for i in self.indices), '%5D'%0A %5D)%0A%0A def __hash__(self):%0A %22%22%22Compute the hash value of a vector.%22%22%22%0A return hash((self.base, self.indices))%0A%0A def __eq__(self, other):%0A %22%22%22Compares the equality of two vectors.%22%22%22%0A return (%0A (isinstance(self, type(other)) or isinstance(other, type(self))) and%0A self.base == other.base and self.indices == other.indices%0A )%0A
|
|
d0d4688a8768dceeeb5d609a05de72fc24ac6b75
|
Create pwned.py
|
pwned/src/pwned.py
|
pwned/src/pwned.py
|
Python
| 0.000001 |
@@ -0,0 +1,571 @@
+import hashlib, sys, urllib.request%0A%0Adef main():%0A%09hash = hashlib.sha1(bytes(sys.argv%5B1%5D, %22utf-8%22))%0A%09digest = hash.hexdigest().upper()%0A%09url = f%22https://api.pwnedpasswords.com/range/%7Bdigest%5B:5%5D%7D%22%0A%0A%09request = urllib.request.Request(url, headers=%7B%22User-Agent%22:%22API-Programming-Exercise%22%7D)%0A%09page = urllib.request.urlopen(request)%0A%0A%09data = (page.read().decode('utf-8').split())%0A%0A%09for i in data:%0A%09%09tmp = i.split(%22:%22)%0A%09%09if digest%5B:5%5D + tmp%5B0%5D == digest:%0A%09%09%09print(f%22%7Bsys.argv%5B1%5D%7D was found%22)%0A%09%09%09print(f%22Hash %7Bdigest%7D, %7Btmp%5B1%5D%7D occurrences%22)%0A%09%09%09%0Aif __name__ == %22__main__%22:%0A%09main()%0A
|
|
aca14378e6f7091abed8f25183b36a36170caa76
|
Fix State ID number to 8 chars limit
|
users/models.py
|
users/models.py
|
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User as AuthUser
# User-related models
class User(models.Model):
'''
Represents an user. Both organizers and participants are considered as
users. This allows usage of the same accounts for the users that became
organizers later.
'''
# Fields accessible from AuthUser:
# username
# first_name
# last_name
# email
# password
# is_staff
# is_active
# is_superuser
# last_login
# date_joined
authuser = models.OneToOneField(AuthUser)
# personal info
date_of_birth = models.DateTimeField(blank=True)
sex = models.CharField(max_length=1, blank=True, choices=(('M', 'male'),
('F', 'female')))
social_security_number = models.CharField(max_length=11, blank=True)
state_id_number = models.CharField(max_length=7, blank=True)
competes = models.ManyToManyField('competitions.Competition',
through='competitions.CompetitionUserRegistration')
# address information
phone_number = models.CharField(max_length=30, blank=True)
parent_phone_number = models.CharField(max_length=30, blank=True)
address = models.ForeignKey('schools.Address')
# school related info
school = models.ForeignKey('schools.School', blank=True)
school_class = models.CharField(max_length=20, blank=True)
classlevel = models.CharField(max_length=2, blank=True,
choices=(('Z2', 'Z2'),
('Z3', 'Z3'),
('Z4', 'Z4'),
('Z5', 'Z5'),
('Z6', 'Z6'),
('Z7', 'Z7'),
('Z8', 'Z8'),
('Z9', 'Z9'),
('S1', 'S1'),
('S2', 'S2'),
('S3', 'S3'),
('S4', 'S4')))
# Fields added via foreign keys:
# camp_set
# campuserinvitation_set
# competitionuserregistration_set
# event_set
# eventuserregistration_set
# usersolution_set
# Fields added via inheritance:
# organizer
def __unicode__(self):
return self.login
class Organizer(User):
'''
Represents an organizer. Organizer can organize multiple competitions
or events.
'''
motto = models.CharField(max_length=50)
# TODO: there are 2 data descriptors added via many-to-many relationship
# in this case it's organized_event_set (custom name due to
# the fact that optional parameter related_name was defined)
# and eventorgregistration_set
# Investigate!
# Fields added via foreign keys:
# competitionorgregistration_set
# eventorgregistration_set
# organized_event_set
# registeredorg
# orgsolution_set
# post_set
# Fields added via inheritance:
# user_ptr
# Register to the admin site
admin.site.register(User)
admin.site.register(Organizer)
|
Python
| 0.001402 |
@@ -952,17 +952,17 @@
_length=
-7
+8
, blank=
|
3b7b9966f84b3560a597b80a346922fb33d55912
|
Revert "[Bug 1241969] don't ignore the requested language when opening /ab-CD/firefox/"
|
bedrock/firefox/urls.py
|
bedrock/firefox/urls.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf.urls import url
from bedrock.redirects.util import redirect
from bedrock.mozorg.util import page
import views
import bedrock.releasenotes.views
from bedrock.releasenotes import version_re
latest_re = r'^firefox(?:/(?P<version>%s))?/%s/$'
firstrun_re = latest_re % (version_re, 'firstrun')
firstrun_learnmore_re = latest_re % (version_re, 'firstrun/learnmore')
secondrun_re = latest_re % (version_re, 'secondrun')
whatsnew_re = latest_re % (version_re, 'whatsnew')
tour_re = latest_re % (version_re, 'tour')
hello_start_re = latest_re % (version_re, 'hello/start')
tracking_protection_re = latest_re % (version_re, 'tracking-protection/start')
platform_re = '(?P<platform>android|ios)'
channel_re = '(?P<channel>beta|aurora|developer|organizations)'
releasenotes_re = latest_re % (version_re, r'(aurora|release)notes')
android_releasenotes_re = releasenotes_re.replace('firefox', 'firefox/android')
ios_releasenotes_re = releasenotes_re.replace('firefox', 'firefox/ios')
sysreq_re = latest_re % (version_re, 'system-requirements')
ios_sysreq_re = sysreq_re.replace('firefox', 'firefox/ios')
urlpatterns = (
redirect(r'^firefox/$', 'firefox.new', name='firefox'),
url(r'^firefox/(?:%s/)?(?:%s/)?all/$' % (platform_re, channel_re),
views.all_downloads, name='firefox.all'),
page('firefox/accounts', 'firefox/accounts.html'),
page('firefox/channel', 'firefox/channel.html'),
redirect('^firefox/channel/android/$', 'firefox.channel'),
page('firefox/desktop', 'firefox/desktop/index.html'),
page('firefox/desktop/fast', 'firefox/desktop/fast.html'),
page('firefox/desktop/customize', 'firefox/desktop/customize.html'),
page('firefox/desktop/tips', 'firefox/desktop/tips.html'),
page('firefox/desktop/trust', 'firefox/desktop/trust.html'),
page('firefox/developer', 'firefox/developer.html'),
page('firefox/features', 'firefox/features.html'),
page('firefox/geolocation', 'firefox/geolocation.html'),
url(r'^firefox/hello/$', views.hello, name='firefox.hello'),
page('firefox/interest-dashboard', 'firefox/interest-dashboard.html'),
page('firefox/android', 'firefox/android/index.html'),
page('firefox/android/faq', 'firefox/android/faq.html'),
page('firefox/ios', 'firefox/ios.html'),
url(r'^firefox/ios/testflight', views.ios_testflight, name='firefox.ios.testflight'),
page('firefox/mobile-download', 'firefox/mobile-download.html'),
page('firefox/products', 'firefox/family/index.html'),
page('firefox/private-browsing', 'firefox/private-browsing.html'),
url('^firefox/send-to-device-post/$', views.send_to_device_ajax,
name='firefox.send-to-device-post'),
url(r'^firefox/sync/$', views.sync, name='firefox.sync'),
page('firefox/unsupported-systems', 'firefox/unsupported-systems.html'),
url(r'^firefox/new/$', views.new, name='firefox.new'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations/organizations.html'),
page('firefox/nightly/firstrun', 'firefox/nightly_firstrun.html'),
url(r'^firefox/installer-help/$', views.installer_help,
name='firefox.installer-help'),
page('firefox/unsupported/warning', 'firefox/unsupported/warning.html'),
page('firefox/unsupported/EOL', 'firefox/unsupported/EOL.html'),
page('firefox/unsupported/mac', 'firefox/unsupported/mac.html'),
page('firefox/unsupported/details', 'firefox/unsupported/details.html'),
# bug 960651
# here because it needs to come after the above rule
redirect(r'(firefox|mobile)/([^/]+)/details(/|/.+\.html)?$', 'firefox.unsupported.details',
locale_prefix=False),
url(r'^firefox/unsupported/win/$', views.windows_billboards),
url('^firefox/dnt/$', views.dnt, name='firefox.dnt'),
url(firstrun_re, views.FirstrunView.as_view(), name='firefox.firstrun'),
url(firstrun_learnmore_re, views.FirstrunLearnMoreView.as_view(),
name='firefox.firstrun.learnmore'),
url(secondrun_re, views.SecondrunView.as_view(), name='firefox.secondrun'),
url(whatsnew_re, views.WhatsnewView.as_view(), name='firefox.whatsnew'),
url(tour_re, views.TourView.as_view(), name='firefox.tour'),
url(hello_start_re, views.HelloStartView.as_view(), name='firefox.hello.start'),
url(tracking_protection_re, views.TrackingProtectionTourView.as_view(),
name='firefox.tracking-protection-tour.start'),
# This dummy page definition makes it possible to link to /firefox/ (Bug 878068)
url('^firefox/$', views.fx_home_redirect, name='firefox'),
page('firefox/os', 'firefox/os/index.html'),
page('mwc', 'firefox/os/mwc-2015-preview.html'),
page('firefox/os/devices', 'firefox/os/devices.html'),
page('firefox/os/devices/tv', 'firefox/os/tv.html'),
page('firefox/pocket', 'firefox/pocket.html'),
url(r'^firefox/windows-10/welcome/$', views.Win10Welcome.as_view(), name='firefox.win10-welcome'),
# Release notes
url('^firefox/(?:%s/)?(?:%s/)?notes/$' % (platform_re, channel_re),
bedrock.releasenotes.views.latest_notes, name='firefox.notes'),
url('firefox/(?:latest/)?releasenotes/$', bedrock.releasenotes.views.latest_notes,
{'product': 'firefox'}),
url('^firefox/(?:%s/)?system-requirements/$' % channel_re,
bedrock.releasenotes.views.latest_sysreq,
{'product': 'firefox'}, name='firefox.sysreq'),
url(releasenotes_re, bedrock.releasenotes.views.release_notes, name='firefox.desktop.releasenotes'),
url(android_releasenotes_re, bedrock.releasenotes.views.release_notes,
{'product': 'Firefox for Android'}, name='firefox.android.releasenotes'),
url(ios_releasenotes_re, bedrock.releasenotes.views.release_notes,
{'product': 'Firefox for iOS'}, name='firefox.ios.releasenotes'),
url(sysreq_re, bedrock.releasenotes.views.system_requirements,
name='firefox.system_requirements'),
url(ios_sysreq_re, bedrock.releasenotes.views.system_requirements,
{'product': 'Firefox for iOS'}, name='firefox.ios.system_requirements'),
url('^firefox/releases/$', bedrock.releasenotes.views.releases_index,
{'product': 'Firefox'}, name='firefox.releases.index'),
# Bug 1108828. Different templates for different URL params.
url('firefox/feedback', views.FeedbackView.as_view(), name='firefox.feedback'),
)
|
Python
| 0 |
@@ -1378,16 +1378,37 @@
firefox'
+, locale_prefix=False
),%0A u
@@ -1691,16 +1691,37 @@
channel'
+, locale_prefix=False
),%0A p
|
806594afc5468d3cee183defba24501516b791f0
|
add cities borders
|
belarus_city_borders.py
|
belarus_city_borders.py
|
Python
| 0.999998 |
@@ -0,0 +1,1508 @@
+from _helpers import cursor_wrap, dump%0A%0A%0A@cursor_wrap%0Adef main(cursor):%0A sql = %22%22%22%0A SELECT ct.osm_id, c.name AS country, '' AS region, '' AS subregion, ct.name AS city, ST_AsGeoJSON(ct.way)%0A FROM osm_polygon c%0A LEFT JOIN osm_polygon ct ON ST_Contains(c.way, ct.way)%0A WHERE c.osm_id = -59065 AND ct.admin_level = '4'%0A AND ct.tags-%3E'place' IN ('city', 'town')%0A%0A UNION%0A%0A SELECT ct.osm_id, c.name AS country, r.name AS region, '' AS subregion, ct.name AS city, ST_AsGeoJSON(ct.way)%0A FROM osm_polygon c%0A LEFT JOIN osm_polygon r ON ST_Contains(c.way, r.way)%0A LEFT JOIN osm_polygon ct ON ST_Contains(r.way, ct.way)%0A WHERE c.osm_id = -59065 AND r.admin_level = '4' AND ct.admin_level = '6'%0A AND ct.tags-%3E'place' IN ('city', 'town')%0A%0A UNION%0A%0A SELECT ct.osm_id, c.name AS country, r.name AS region, s.name AS subregion, ct.name AS city, ST_AsGeoJSON(ct.way)%0A FROM osm_polygon c%0A LEFT JOIN osm_polygon r ON ST_Contains(c.way, r.way)%0A LEFT JOIN osm_polygon s ON ST_Contains(r.way, s.way)%0A LEFT JOIN osm_polygon ct ON ST_Contains(s.way, ct.way)%0A WHERE c.osm_id = -59065 AND r.admin_level = '4' AND s.admin_level = '6'%0A AND ct.tags-%3E'place' IN ('city', 'town')%0A %22%22%22%0A cursor.execute(sql)%0A dump(__file__, sorted(cursor.fetchall(), key=lambda item: item%5B1:5%5D),%0A ('osmid', 'country', 'region', 'subregion', 'city', 'geojson'))%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
fdb901a59e8dd61892f5033efe49e3bbbdae097f
|
Create CNlab1.py
|
CNlab1.py
|
CNlab1.py
|
Python
| 0.000002 |
@@ -0,0 +1,1477 @@
+#To check the validity of ip address%0A%0Aimport sys%0Aimport textwrap%0A%0Adef valid(ip):%0A%0A if ip.count('.')!=3:%0A print(%22Invalid%22)%0A sys.exit(0)%0A ipl=%5B%5D%0A ipl=ip.split('.')%0A for i in ipl:%0A if not i.isdigit():%0A print(%22Invalid%22)%0A sys.exit(0)%0A if int(i)%3E255:%0A print(%22Invalid%22)%0A sys.exit(0)%0A%0A else:%0A print(%22Valid%22)%0A%0A%0A#To calculate bit mask%0A%0Ainp=raw_input(%22Enter the ip address%5Cn%22)%0Ali=inp.split('/')%0Aipv=li%5B0%5D%0Avalid(li%5B0%5D)%0An=int(li%5B1%5D)%0Ah=32-int(li%5B1%5D)%0Amask= '1'* n + '0'*h%0Amaskd= '.'.join(str(int(i,2)) for i in textwrap.wrap(mask, 8))%0Aprint %22Mask : %22, maskd%0A%0Amaskd_list= maskd.split('.')%0Aipv_list=ipv.split('.')%0A%0A#To calculate network id%0Ak=0%0Anet_id=%5B%5D%0Afor i in range(0,4):%0A net_id.append(str(int(maskd_list%5Bk%5D) & int(ipv_list%5Bk%5D)))%0A k+=1%0A%0Aprint %22Network id : %22 , '.'.join(net_id)%0A%0A#To calculate brodcast address%0Azoo=%5B%5D%0Afor i in net_id:%0A zoo.append(%22%7B0:08b%7D%22.format(int(i)))%0A%0Azoos = ''.join(zoo)%0Abroad=%5B%5D%0A%0Afor i in textwrap.wrap(zoos%5B:n%5D + str(int(zoos%5Bn:%5D,2) %7C int( '1'* h)), 8):%0A broad.append(str(int(i,2)))%0A%0Aprint('Broadcast address : ', '.'.join(broad))%0A%0A#To calculate no. of subnets%0Aprint %22Number of subnets%22, 2 ** (n)%0A%0A#To calculate nu. of hosts%0Aprint %22Number of hosts%22, (2 ** (32-n)) - 2%0A%0A%0A#To print first address%0Aprint %22First address : %22 + '.'.join(net_id%5B:3%5D)+ '.' + str(int(net_id%5B3%5D) + 1)%0A%0A#To print last address%0Aprint %22Last address : %22 + '.'.join(broad%5B:3%5D) + '.' + str(int(broad%5B3%5D) - 1)%0A%0A%0A
|
|
f16dcf6fe2d53be0444faad9f265781282201d95
|
Use consistent quotes
|
colorama/ansi.py
|
colorama/ansi.py
|
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
OSC = '\033]'
BEL = '\007'
def code_to_chars(code):
return CSI + str(code) + 'm'
def set_title(title):
return OSC + "2;" + title + BEL
def clear_screen(mode=2):
return CSI + str(mode) + "J"
def clear_line(mode=2):
return CSI + str(mode) + "K"
class AnsiCodes(object):
def __init__(self, codes):
for name in dir(codes):
if not name.startswith('_'):
value = getattr(codes, name)
setattr(self, name, code_to_chars(value))
class AnsiCursor(object):
def UP(self, n=1):
return CSI + str(n) + "A"
def DOWN(self, n=1):
return CSI + str(n) + "B"
def FORWARD(self, n=1):
return CSI + str(n) + "C"
def BACK(self, n=1):
return CSI + str(n) + "D"
def POS(self, x=1, y=1):
return CSI + str(y) + ";" + str(x) + "H"
class AnsiFore:
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
RESET = 39
# These are fairly well supported, but not part of the standard.
LIGHTBLACK_EX = 90
LIGHTRED_EX = 91
LIGHTGREEN_EX = 92
LIGHTYELLOW_EX = 93
LIGHTBLUE_EX = 94
LIGHTMAGENTA_EX = 95
LIGHTCYAN_EX = 96
LIGHTWHITE_EX = 97
class AnsiBack:
BLACK = 40
RED = 41
GREEN = 42
YELLOW = 43
BLUE = 44
MAGENTA = 45
CYAN = 46
WHITE = 47
RESET = 49
# These are fairly well supported, but not part of the standard.
LIGHTBLACK_EX = 100
LIGHTRED_EX = 101
LIGHTGREEN_EX = 102
LIGHTYELLOW_EX = 103
LIGHTBLUE_EX = 104
LIGHTMAGENTA_EX = 105
LIGHTCYAN_EX = 106
LIGHTWHITE_EX = 107
class AnsiStyle:
BRIGHT = 1
DIM = 2
NORMAL = 22
RESET_ALL = 0
Fore = AnsiCodes( AnsiFore )
Back = AnsiCodes( AnsiBack )
Style = AnsiCodes( AnsiStyle )
Cursor = AnsiCursor()
|
Python
| 0 |
@@ -349,12 +349,12 @@
C +
-%222;%22
+'2;'
+ t
@@ -424,11 +424,11 @@
) +
-%22J%22
+'J'
%0A%0Ade
@@ -482,11 +482,11 @@
) +
-%22K%22
+'K'
%0A%0A%0Ac
@@ -801,11 +801,11 @@
) +
-%22A%22
+'A'
%0A
@@ -860,11 +860,11 @@
) +
-%22B%22
+'B'
%0A
@@ -922,11 +922,11 @@
) +
-%22C%22
+'C'
%0A
@@ -981,11 +981,11 @@
) +
-%22D%22
+'D'
%0A
@@ -1044,11 +1044,11 @@
) +
-%22;%22
+';'
+ s
@@ -1059,11 +1059,11 @@
) +
-%22H%22
+'H'
%0A%0A%0Ac
@@ -2191,16 +2191,18 @@
0%0A%0AFore
+
= AnsiCo
@@ -2222,16 +2222,18 @@
)%0ABack
+
= AnsiCo
@@ -2254,16 +2254,17 @@
)%0AStyle
+
= AnsiCo
|
4a261bd97de5868ff6065ac69345d3bef38563f1
|
Check history_object in historical records
|
simple_history/tests/tests.py
|
simple_history/tests/tests.py
|
from datetime import datetime, timedelta
from django.test import TestCase
from .models import Poll, Choice
today = datetime(2021, 1, 1, 10, 0)
tomorrow = today + timedelta(days=1)
class HistoricalRecordsTest(TestCase):
def assertDatetimesEqual(self, time1, time2):
self.assertAlmostEqual(time1, time2, delta=timedelta(seconds=2))
def assertRecordValues(self, record, values_dict):
for key, value in values_dict.items():
self.assertEqual(getattr(record, key), value)
def test_create(self):
p = Poll(question="what's up?", pub_date=today)
p.save()
history = p.history.all()
record, = history
self.assertRecordValues(record, {
'question': "what's up?",
'pub_date': today,
'id': p.id,
'history_type': "+"
})
self.assertDatetimesEqual(record.history_date, datetime.now())
def test_update(self):
Poll.objects.create(question="what's up?", pub_date=today)
p = Poll.objects.get()
p.pub_date = tomorrow
p.save()
history = p.history.all()
update_record, create_record = history
self.assertRecordValues(create_record, {
'question': "what's up?",
'pub_date': today,
'id': p.id,
'history_type': "+"
})
self.assertRecordValues(update_record, {
'question': "what's up?",
'pub_date': tomorrow,
'id': p.id,
'history_type': "~"
})
def test_delete(self):
p = Poll.objects.create(question="what's up?", pub_date=today)
poll_id = p.id
p.delete()
history = Poll.history.all()
delete_record, create_record = history
self.assertRecordValues(create_record, {
'question': "what's up?",
'pub_date': today,
'id': poll_id,
'history_type': "+"
})
self.assertRecordValues(delete_record, {
'question': "what's up?",
'pub_date': today,
'id': poll_id,
'history_type': "-"
})
class RegisterTest(TestCase):
def test_register_no_args(self):
self.assertEqual(len(Choice.history.all()), 0)
poll = Poll.objects.create(pub_date=today)
choice = Choice.objects.create(poll=poll, votes=0)
self.assertEqual(len(choice.history.all()), 1)
class HistoryManagerTest(TestCase):
def test_most_recent(self):
poll = Poll.objects.create(question="what's up?", pub_date=today)
poll.question = "how's it going?"
poll.save()
poll.question = "why?"
poll.save()
poll.question = "how?"
most_recent = poll.history.most_recent()
self.assertEqual(most_recent.__class__, Poll)
self.assertEqual(most_recent.question, "why?")
def test_as_of(self):
poll = Poll.objects.create(question="what's up?", pub_date=today)
poll.question = "how's it going?"
poll.save()
poll.question = "why?"
poll.save()
poll.question = "how?"
most_recent = poll.history.most_recent()
self.assertEqual(most_recent.question, "why?")
times = [r.history_date for r in poll.history.all()]
question_as_of = lambda time: poll.history.as_of(time).question
self.assertEqual(question_as_of(times[0]), "why?")
self.assertEqual(question_as_of(times[1]), "how's it going?")
self.assertEqual(question_as_of(times[2]), "what's up?")
|
Python
| 0 |
@@ -501,16 +501,242 @@
, value)
+%0A self.assertEqual(record.history_object.__class__, Poll)%0A for key, value in values_dict.items():%0A if key != 'history_type':%0A self.assertEqual(getattr(record.history_object, key), value)
%0A%0A de
|
bf6f58d5958275070c1018174217873ea08db904
|
Add test pull task
|
nodeconductor/structure/tests/tasks.py
|
nodeconductor/structure/tests/tasks.py
|
Python
| 0.000074 |
@@ -0,0 +1,336 @@
+from celery import shared_task%0A%0Afrom nodeconductor.core import utils as core_utils%0A%0A%0A@shared_task%0Adef pull_instance(serialized_instance, pulled_disk):%0A %22%22%22 Test-only task that allows to emulate pull operation %22%22%22%0A instance = core_utils.deserialize_instance(serialized_instance)%0A instance.disk = pulled_disk%0A instance.save()%0A
|
|
7ce8c06c5447d89f941d482c84693e432384def6
|
rename `file` to `filename` for clarity.
|
pysellus/loader.py
|
pysellus/loader.py
|
import os
import sys
from inspect import isfunction
from importlib import import_module
def load(path):
if _is_python_file(path):
sys.path.insert(0, os.path.dirname(path))
module = import_module(_get_module_name_from_path(path))
return _get_checks_from_module(module)
functions = []
for module in _get_modules(path):
functions += _get_checks_from_module(module)
return functions
def _get_module_name_from_path(path):
return _remove_file_extension(path.split('/')[-1])
def _get_checks_from_module(module):
"""
Gets all setup functions from the given module.
Setup functions are required to start with 'pscheck_'
"""
functions = []
for name in dir(module):
value = getattr(module, name)
if isfunction(value) and name.startswith('pscheck_'):
functions.append(value)
return functions
def _get_modules(directory):
sys.path.insert(0, directory)
return [
import_module(filename)
for filename in _get_python_files(directory)
]
def _get_python_files(directory):
return [
_remove_file_extension(file)
for file in os.listdir(directory)
if not file.startswith('__') and _is_python_file(file)
]
def _is_python_file(filename):
return filename.endswith('.py')
def _remove_file_extension(filename):
return filename[:-3]
|
Python
| 0 |
@@ -475,37 +475,32 @@
return _remove_
-file_
extension(path.s
@@ -1110,37 +1110,32 @@
_remove_
-file_
extension(file)%0A
@@ -1128,24 +1128,28 @@
tension(file
+name
)%0A fo
@@ -1154,16 +1154,20 @@
for file
+name
in os.l
@@ -1203,16 +1203,20 @@
not file
+name
.startsw
@@ -1249,16 +1249,20 @@
ile(file
+name
)%0A %5D%0A
@@ -1328,24 +1328,24 @@
th('.py')%0A%0A%0A
+
def _remove_
@@ -1348,13 +1348,8 @@
ove_
-file_
exte
|
cc5f55fa6eb6d0ecaaef1c1e269fb40c2731fef5
|
Add test helpers
|
src/lib/test_helpers.py
|
src/lib/test_helpers.py
|
Python
| 0.000001 |
@@ -0,0 +1,1608 @@
+# Copyright (C) 2015 Google Inc., authors, and contributors %3Csee AUTHORS file%3E%0A# Licensed under http://www.apache.org/licenses/LICENSE-2.0 %3Csee LICENSE file%3E%0A# Created By: [email protected]%0A# Maintained By: [email protected]%0A%0A%22%22%22%0AUtility classes for page objects used in tests.%0A%0ADetails:%0AMost of the tests require a sequence of primitive methods of the page%0Aobject. If the sequence repeats itself among tests, it should be shared in%0Athis module.%0A%22%22%22%0A%0Aimport uuid%0Afrom lib import base%0Afrom lib.constants.test import create_new_program%0A%0A%0Aclass LhnMenu(base.Test):%0A @staticmethod%0A def create_new_program():%0A pass%0A%0A%0Aclass ModalNewProgramPage(base.Test):%0A %22%22%22Methods for simulating common user actions%22%22%22%0A%0A @staticmethod%0A def enter_test_data(modal):%0A %22%22%22Fills out all fields in the modal%0A%0A Args:%0A modal (lib.page.modal.new_program.NewProgramModal)%0A %22%22%22%0A unique_id = str(uuid.uuid4())%0A%0A modal.enter_title(create_new_program.TITLE + unique_id)%0A modal.enter_description(%0A create_new_program.DESCRIPTION_SHORT)%0A modal.enter_notes(%0A create_new_program.NOTES_SHORT)%0A modal.enter_code(create_new_program.CODE + unique_id)%0A modal.filter_and_select_primary_contact(%22example%22)%0A modal.filter_and_select_secondary_contact(%22example%22)%0A modal.enter_program_url(%0A create_new_program.PROGRAM_URL)%0A modal.enter_reference_url(%0A create_new_program.REFERENCE_URL)%0A modal.enter_effective_date_start_month()%0A modal.enter_stop_date_end_month()%0A
|
|
8e7350cbfc96541d9a3ddc970309c60793bb4126
|
fix TermsFacet
|
corehq/apps/es/facets.py
|
corehq/apps/es/facets.py
|
class FacetResult(object):
def __init__(self, raw, facet):
self.facet = facet
self.raw = raw
self.result = raw.get(self.facet.name, {}).get(self.facet.type, {})
class Facet(object):
name = None
type = None
params = None
result_class = FacetResult
def __init__(self):
raise NotImplementedError()
def parse_result(self, result):
return self.result_class(result, self)
class TermsResult(FacetResult):
def counts_by_term(self):
return {d['term']: d['count'] for d in self.result}
class TermsFacet(Facet):
type = "terms"
result_class = TermsResult
def __init__(self, name, term, size=None):
assert(name.isalnum(), "name must be a valid python variable name")
self.name = name
self.params = {
"field": term,
}
if size is not None:
self.params["size"] = size
class DateHistogram(Facet):
type = "date_histogram"
def __init__(self, name, datefield, interval):
self.name = name
self.params = {
"field": datefield,
"interval": interval
}
|
Python
| 0.000001 |
@@ -660,18 +660,18 @@
lf,
-name, term
+term, name
, si
|
04ded12c05b20fc3a25956712f8e0fb1723c3edb
|
Add a snippet (python/warnings).
|
python/warnings.py
|
python/warnings.py
|
Python
| 0.000004 |
@@ -0,0 +1,456 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2012 J%C3%A9r%C3%A9mie DECOCK (http://www.jdhp.org)%0A%0Aimport warnings%0A%0Adef custom_formatwarning(message, category, filename, lineno, line=%22%22):%0A %22%22%22Ignore everything except the message.%22%22%22%0A return %22Warning: %22 + str(message) + %22%5Cn%22%0A%0Adef main():%0A %22%22%22Main function%22%22%22%0A%0A warnings.formatwarning = custom_formatwarning%0A%0A warnings.warn(%22Foo%22, UserWarning)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A%0A
|
|
630413b6bdc385095fe8da549b691d54fc6a4504
|
Add ITWeek.py
|
ITWeek.py
|
ITWeek.py
|
Python
| 0 |
@@ -0,0 +1,351 @@
+import requests%0D%0Afrom bs4 import BeautifulSoup%0D%0A%0D%0Adef main():%0D%0A url = 'https://ex-portal3.reed.jp/list/SODECS2017_ja.html'%0D%0A res = requests.get(url)%0D%0A soup = BeautifulSoup(res.content, 'html.parser')%0D%0A companies = soup.find_all('tr')%0D%0A for company in companies:%0D%0A print(company.text)%0D%0A%0D%0Aif __name__ == '__main__':%0D%0A main()%0D%0A%0D%0A
|
|
1f71153cf814f7d34835cea6eafe44683035d874
|
Add compare_files.py
|
compare_files.py
|
compare_files.py
|
Python
| 0.000002 |
@@ -0,0 +1,497 @@
+import difflib%0A%0Adef compare_files(filename1, filename2):%0A f = open(filename1, %22r%22)%0A filelines1 = f.readlines()%0A f.close()%0A f = open(filename2, %22r%22)%0A filelines2 = f.readlines()%0A f.close()%0A diffs = difflib.context_diff(filelines1,%0A filelines2,%0A fromfile=filename1,%0A tofile=filename2)%0A count = 0%0A for line in diffs:%0A print line,%0A count += 1%0A return count == 0%0A
|
|
3ce2e0b8825c7abc219a812c5abda45184fbfdec
|
add wot wikia plugin
|
plugins/wotwikia.py
|
plugins/wotwikia.py
|
Python
| 0 |
@@ -0,0 +1,1425 @@
+%22%22%22 WoT Wikia Plugin (botwot plugins.wiki) %22%22%22%0A%0A# Copyright 2015 Ray Schulz %3Chttps://rascul.io%3E%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A%0Aimport json%0A%0A%0Aimport requests%0A%0Afrom pyaib.plugins import keyword, plugin_class%0A%0A%0A@plugin_class%0Aclass WotWikia(object):%0A%09def __init__(self, context, config):%0A%09%09pass%0A%09%0A%09%0A%09@keyword(%22wot%22)%0A%09def keyword_wot(self, context, msg, trigger, args, kargs):%0A%09%09%22%22%22%0A%09%09%3Cquery%3E - Search the WoT Wikia for %3Cquery%3E %0A%09%09%22%22%22%0A%09%09%0A%09%09target_user = %22%22%0A%09%09query = %22%22%0A%09%09if len(args) %3E= 3 and args%5B-2%5D == %22%7C%22:%0A%09%09%09target_user = args%5B-1%5D%0A%09%09%09query = %22 %22.join(args%5B:-2%5D)%0A%09%09else:%0A%09%09%09query = %22 %22.join(args)%0A%09%09%0A%09%09%0A%09%09url = %22http://wot.wikia.com/api/v1/Search/List%22%0A%09%09payload = %7B'query': query, 'limit': 1%7D%0A%09%09r = requests.get(url, params=payload)%0A%09%09j = json.loads(r.text)%0A%09%09if j and 'items' in j:%0A%09%09%09if target_user:%0A%09%09%09%09msg.reply(%22%25s: %25s%22 %25 (target_user, j%5B'items'%5D%5B0%5D%5B'url'%5D))%0A%09%09%09else:%0A%09%09%09%09msg.reply(j%5B'items'%5D%5B0%5D%5B'url'%5D)%0A%0A%0A%0A
|
|
46818f540d48bd967e8e0e5d846f0757f2ca6c1c
|
Add test for set_shard()
|
deepchem/data/tests/test_setshard.py
|
deepchem/data/tests/test_setshard.py
|
Python
| 0.000001 |
@@ -0,0 +1,541 @@
+import deepchem as dc%0Aimport numpy as np%0A%0A%0Adef test_setshard_with_X_y():%0A %22%22%22Test setharding on a simple example%22%22%22%0A X = np.random.rand(10, 3)%0A y = np.random.rand(10,)%0A dataset = dc.data.DiskDataset.from_numpy(X, y)%0A assert dataset.get_shape()%5B0%5D%5B0%5D == 10%0A assert dataset.get_shape()%5B1%5D%5B0%5D == 10%0A for i, (X, y, w, ids) in enumerate(dataset.itershards()):%0A X = X%5B1:%5D%0A y = y%5B1:%5D%0A w = w%5B1:%5D%0A ids = ids%5B1:%5D%0A dataset.set_shard(i, X, y, w, ids)%0A assert dataset.get_shape()%5B0%5D%5B0%5D == 9%0A assert dataset.get_shape()%5B1%5D%5B0%5D == 9%0A
|
|
6ad081e91e337e1627b70674109f45ba35248f8c
|
Add missing migration file to the repo
|
zou/migrations/versions/e839d6603c09_add_person_id_to_shot_history.py
|
zou/migrations/versions/e839d6603c09_add_person_id_to_shot_history.py
|
Python
| 0 |
@@ -0,0 +1,1145 @@
+%22%22%22add person id to shot history%0A%0ARevision ID: e839d6603c09%0ARevises: 346250b5304c%0ACreate Date: 2020-12-14 12:00:19.045783%0A%0A%22%22%22%0Afrom alembic import op%0Aimport sqlalchemy as sa%0Aimport sqlalchemy_utils%0Aimport sqlalchemy_utils%0Aimport uuid%0A%0A# revision identifiers, used by Alembic.%0Arevision = 'e839d6603c09'%0Adown_revision = '346250b5304c'%0Abranch_labels = None%0Adepends_on = None%0A%0A%0Adef upgrade():%0A # ### commands auto generated by Alembic - please adjust! ###%0A op.add_column('entity_version', sa.Column('person_id', sqlalchemy_utils.types.uuid.UUIDType(binary=False), default=uuid.uuid4, nullable=True))%0A op.create_index(op.f('ix_entity_version_person_id'), 'entity_version', %5B'person_id'%5D, unique=False)%0A op.create_foreign_key(None, 'entity_version', 'person', %5B'person_id'%5D, %5B'id'%5D)%0A # ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A # ### commands auto generated by Alembic - please adjust! ###%0A op.drop_constraint(None, 'entity_version', type_='foreignkey')%0A op.drop_index(op.f('ix_entity_version_person_id'), table_name='entity_version')%0A op.drop_column('entity_version', 'person_id')%0A # ### end Alembic commands ###%0A
|
|
0538523f617ec1d410861b52a647c788c06c267a
|
Fix llg tests.
|
pyoommf/test_llg.py
|
pyoommf/test_llg.py
|
from llg import LLG
def test_llg_mif():
t = 1.5e-9
m_init = (0, 1, 0)
Ms = 1e6
alpha = 0.01
gamma = 2.21e5
llg = LLG(t, m_init, Ms, alpha, gamma)
mif_string = llg.get_mif()
lines = mif_string.split('\n')
assert 'Specify Oxs_RungeKuttaEvolve {' in lines[0]
line2 = lines[1].split()
assert float(line2[1]) == alpha
line3 = lines[2].split()
assert float(line3[1]) == gamma
line8 = lines[8].split()
assert float(line8[1]) == t
line11 = lines[11].split()
assert float(line11[1]) == Ms
line13 = lines[13].split()
assert float(line13[1][1:]) == m_init[0]
assert float(line13[2]) == m_init[1]
assert float(line13[3][:-1]) == m_init[2]
def test_llg_formatting():
t = 1.5e-9
m_init = (0, 1, 0)
Ms = 1e6
alpha = 0.01
gamma = 2.21e5
llg = LLG(t, m_init, Ms, alpha, gamma)
mif_string = llg.get_mif()
assert mif_string[0] == 'S'
assert mif_string[-1] == '\n'
assert mif_string[-2] == '\n'
|
Python
| 0.000001 |
@@ -117,32 +117,49 @@
ma = 2.21e5%0A
+name = 'llgtest'%0A
%0A llg = LLG(t
@@ -176,32 +176,38 @@
Ms, alpha, gamma
+, name
)%0A%0A mif_strin
@@ -847,24 +847,45 @@
ma = 2.21e5%0A
+ name = 'llgtest'%0A
%0A llg
@@ -918,16 +918,22 @@
a, gamma
+, name
)%0A%0A m
|
22252d6978f237a2a46415dcf54d4adbed92b1ce
|
Add LLG tests.
|
pyoommf/test_llg.py
|
pyoommf/test_llg.py
|
Python
| 0 |
@@ -0,0 +1,1016 @@
+from llg import LLG%0A%0Adef test_llg_mif():%0A t = 1.5e-9%0A m_init = (0, 1, 0)%0A Ms = 1e6%0A alpha = 0.01%0A gamma = 2.21e5%0A %0A llg = LLG(t, m_init, Ms, alpha, gamma)%0A%0A mif_string = llg.get_mif()%0A%0A lines = mif_string.split('%5Cn')%0A%0A assert 'Specify Oxs_RungeKuttaEvolve %7B' in lines%5B0%5D%0A line2 = lines%5B1%5D.split()%0A assert float(line2%5B1%5D) == alpha%0A line3 = lines%5B2%5D.split()%0A assert float(line3%5B1%5D) == gamma%0A line8 = lines%5B8%5D.split()%0A assert float(line8%5B1%5D) == t%0A line11 = lines%5B11%5D.split()%0A assert float(line11%5B1%5D) == Ms%0A line13 = lines%5B13%5D.split()%0A assert float(line13%5B1%5D%5B1:%5D) == m_init%5B0%5D%0A assert float(line13%5B2%5D) == m_init%5B1%5D%0A assert float(line13%5B3%5D%5B:-1%5D) == m_init%5B2%5D%0A%0Adef test_llg_formatting():%0A t = 1.5e-9%0A m_init = (0, 1, 0)%0A Ms = 1e6%0A alpha = 0.01%0A gamma = 2.21e5%0A %0A llg = LLG(t, m_init, Ms, alpha, gamma)%0A%0A mif_string = llg.get_mif()%0A%0A assert mif_string%5B0%5D == 'S'%0A assert mif_string%5B-1%5D == '%5Cn'%0A assert mif_string%5B-2%5D == '%5Cn'%0A
|
|
b21fbb09b33e40a33ad3ea33b0394fed421c8a6e
|
add num02
|
pythonTest/num02.py
|
pythonTest/num02.py
|
Python
| 0.999971 |
@@ -0,0 +1,160 @@
+def reverse(x):%0D%0A changeTuple=tuple(x)%0D%0A reverseTuple=changeTuple%5B::-1%5D%0D%0A print(''.join(reverseTuple))%0D%0A%0D%0Atest = %22this is test string%22%0D%0Areverse(test)%0D%0A
|
|
edc35e4aefe336eb1bf02dbf7104925389276fa6
|
Add shellcheck for sh filetype
|
pythonx/lints/sh.py
|
pythonx/lints/sh.py
|
Python
| 0 |
@@ -0,0 +1,428 @@
+# -*- coding: utf-8 -*-%0A%0Afrom validator import Validator%0A%0A%0Aclass Sh(Validator):%0A __filetype__ = %22sh%22%0A%0A checker = %22shellcheck%22%0A args = %22-x -f gcc%22%0A regex = r%22%22%22%0A .+:%0A (?P%3Clnum%3E%5Cd+):%0A (?P%3Ccol%3E%5Cd+):%0A .*%0A %5Cs%0A (%0A (?P%3Cerror%3Eerror)%0A %7C%0A (?P%3Cwarning%3Ewarning)%0A ):%0A %5Cs%0A (?P%3Ctext%3E.*)%22%22%22%0A
|
|
c25cebf31648466111cb3d576e0a398bb4220ccf
|
Add test for sabnzbd cleanupfilename.py
|
sabnzbd/test_cleanupfilename.py
|
sabnzbd/test_cleanupfilename.py
|
Python
| 0.000001 |
@@ -0,0 +1,826 @@
+import unittest%0Afrom cleanupfilename import rename%0A%0A%0Aclass TestRename(unittest.TestCase):%0A files = %5B%5D%0A dirs = %5B%5D%0A%0A def setUp(self):%0A self.files = %5B('filename-sample.x264.mp4', 'filename.mp4'),%0A ('filename.mp4', 'filename.mp4')%5D%0A self.dirs = %5B('filename sample mp4', 'filename'),%0A ('filename 540p', 'filename'),%0A ('filename %5Bweb-DL%5D part001.', 'filename'),%0A ('actual.file.name-1080p.BluRay.x264-GECKOS%5Brarbg%5D', 'actual file name'),%0A %5D%0A%0A def test_list(self):%0A for file, output in self.files:%0A self.assertEqual(rename(file, False), output)%0A for file, output in self.dirs:%0A self.assertEqual(rename(file, True), output)%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
d56b1623a278d61ff8b113b95534ce4dd6682e25
|
fix bug 1018349 - migration
|
alembic/versions/1baef149e5d1_bug_1018349_add_coalesce_to_max_sort_.py
|
alembic/versions/1baef149e5d1_bug_1018349_add_coalesce_to_max_sort_.py
|
Python
| 0 |
@@ -0,0 +1,684 @@
+%22%22%22bug 1018349 - add COALESCE to max(sort) when adding a new product%0A%0ARevision ID: 1baef149e5d1%0ARevises: 26521f842be2%0ACreate Date: 2014-06-25 15:04:37.934064%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '1baef149e5d1'%0Adown_revision = '26521f842be2'%0A%0Afrom alembic import op%0Afrom socorro.lib import citexttype, jsontype, buildtype%0Afrom socorro.lib.migrations import fix_permissions, load_stored_proc%0A%0Aimport sqlalchemy as sa%0Afrom sqlalchemy import types%0Afrom sqlalchemy.dialects import postgresql%0Afrom sqlalchemy.sql import table, column%0A%0A%0Adef upgrade():%0A load_stored_proc(op, %5B'add_new_product.sql'%5D)%0A%0Adef downgrade():%0A load_stored_proc(op, %5B'add_new_product.sql'%5D)%0A
|
|
d836571a8dff59371d156dffea7290228305ca17
|
add tests for reading shapefiles via ogr
|
tests/python_tests/ogr_test.py
|
tests/python_tests/ogr_test.py
|
Python
| 0 |
@@ -0,0 +1,1703 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Afrom nose.tools import *%0Afrom utilities import execution_path%0A%0Aimport os, mapnik%0A%0Adef setup():%0A # All of the paths used are relative, if we run the tests%0A # from another directory we need to chdir()%0A os.chdir(execution_path('.'))%0A%0Aif 'ogr' in mapnik.DatasourceCache.instance().plugin_names():%0A %0A # Shapefile initialization%0A def test_shapefile_init():%0A s = mapnik.Ogr(file='../../demo/data/boundaries.shp',layer_by_index=0)%0A %0A e = s.envelope()%0A %0A assert_almost_equal(e.minx, -11121.6896651, places=7)%0A assert_almost_equal(e.miny, -724724.216526, places=6)%0A assert_almost_equal(e.maxx, 2463000.67866, places=5)%0A assert_almost_equal(e.maxy, 1649661.267, places=3)%0A %0A # Shapefile properties%0A def test_shapefile_properties():%0A s = mapnik.Ogr(file='../../demo/data/boundaries.shp',layer_by_index=0,encoding='latin1')%0A f = s.features_at_point(s.envelope().center()).features%5B0%5D%0A %0A eq_(f%5B'CGNS_FID'%5D, u'6f733341ba2011d892e2080020a0f4c9')%0A eq_(f%5B'COUNTRY'%5D, u'CAN')%0A eq_(f%5B'F_CODE'%5D, u'FA001')%0A eq_(f%5B'NAME_EN'%5D, u'Quebec')%0A # this seems to break if icu data linking is not working%0A eq_(f%5B'NOM_FR'%5D, u'Qu%5Cxe9bec')%0A eq_(f%5B'NOM_FR'%5D, u'Qu%C3%A9bec')%0A eq_(f%5B'Shape_Area'%5D, 1512185733150.0)%0A eq_(f%5B'Shape_Leng'%5D, 19218883.724300001)%0A %0A # Check that the deprecated interface still works,%0A # remove me once the deprecated code is cleaned up%0A eq_(f.properties%5B'Shape_Leng'%5D, 19218883.724300001)%0A%0A%0A%0Aif __name__ == %22__main__%22:%0A setup()%0A %5Beval(run)() for run in dir() if 'test_' in run%5D%0A %0A
|
|
bf8b19d19ea2a5f39cba90ca815560a89e476c6c
|
Create Output.py
|
Output.py
|
Output.py
|
Python
| 0.000108 |
@@ -0,0 +1,418 @@
+import os, time, sys%0Afrom threading import Thread%0Apipe_name = '/Users/stevenrelin/Documents/pipe_eye.txt'%0A%0Adef child( ):%0A pipeout = os.open(pipe_name, os.O_WRONLY)%0A counter = 0%0A while True:%0A time.sleep(1)%0A os.write(pipeout, 'Number %2503d%5Cn' %25 counter)%0A counter = (counter+1) %25 5%0A %0Aif not os.path.exists(pipe_name):%0A os.mkfifo(pipe_name) %0A %0At = Thread(target=child)%0At.start()%0A
|
|
5f20962d300850200ed796f941bf98662736d4da
|
Add server.py to serve files in the user's specified share dir
|
sandwich/server.py
|
sandwich/server.py
|
Python
| 0 |
@@ -0,0 +1,1145 @@
+from os import curdir, sep, path%0Aimport time%0Afrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer%0A%0Aimport config%0A%0Aclass StaticServeHandler(BaseHTTPRequestHandler):%0A%0A def do_GET(self):%0A%0A if not config.shared_directory:%0A self.send_error(404, 'User not sharing files')%0A return%0A%0A try:%0A f = open(path.expanduser(config.shared_directory) + self.path, 'rb')%0A self.send_response(200)%0A self.end_headers()%0A self.wfile.write(f.read())%0A f.close()%0A return%0A%0A except IOError:%0A self.send_error(404,'File Not Found: %25s' %25 self.path)%0A%0A%0Aclass SandwichServer(object):%0A%0A def __init__(self, ):%0A pass%0A%0A def run(self, port):%0A try:%0A self.port = port%0A self.server = HTTPServer(('', self.port), StaticServeHandler)%0A print 'started httpserver...'%0A self.server.serve_forever()%0A except KeyboardInterrupt:%0A print '%5EC received, shutting down server'%0A self.server.socket.close()%0A%0A%0A%0Aif __name__ == '__main__':%0A ss = SandwichServer()%0A ss.run(8000)%0A%0A
|
|
d774bb7caa9637e4d453e19fcc43ee7b9b17702c
|
add script for computing WWA % times
|
scripts/sbw/wfo_time_percent.py
|
scripts/sbw/wfo_time_percent.py
|
Python
| 0 |
@@ -0,0 +1,1231 @@
+import iemdb%0Aimport numpy%0Aimport network%0A%0Ant = network.Table(%22WFO%22)%0A%0APOSTGIS = iemdb.connect('postgis', bypass=True)%0Apcursor = POSTGIS.cursor()%0A%0Aimport mx.DateTime%0A%0Asts = mx.DateTime.DateTime(2005,10,1)%0Aets = mx.DateTime.DateTime(2013,1,1)%0Ainterval = mx.DateTime.RelativeDateTime(hours=3)%0A%0Abins = (ets - sts).minutes%0A%0Afor wfo in nt.sts.keys():%0A wfo = wfo%5B-3:%5D%0A counts = numpy.zeros( (int(bins)), 'f')%0A%0A pcursor.execute(%22%22%22SELECT distinct issue, expire from warnings where wfo = '%25s'%0A and issue %3E '2005-10-01' and expire %3C '2013-01-01' and gtype = 'C'%0A and phenomena = 'SC' %22%22%22 %25 (wfo,))%0A %0A for row in pcursor:%0A issue = mx.DateTime.strptime(row%5B0%5D.strftime(%22%25Y%25m%25d%25H%25M%22), %22%25Y%25m%25d%25H%25M%22) %0A expire = mx.DateTime.strptime(row%5B1%5D.strftime(%22%25Y%25m%25d%25H%25M%22), %22%25Y%25m%25d%25H%25M%22)%0A %0A idx1 = int((issue - sts).minutes)%0A idx2 = int((expire - sts).minutes)%0A counts%5Bidx1:idx2%5D = 1%0A %0A print %22%25s,%25.4f%22 %25 (wfo, numpy.sum( counts ) / float(bins))%0A %0A pcursor.execute(%22%22%22INSERT into ferree3(wfo, percentage) values (%25s,%25s)%22%22%22,%0A (wfo, float(numpy.sum( counts ) / float(bins))))%0A POSTGIS.commit()%0A %0Apcursor.close()%0APOSTGIS.commit()%0APOSTGIS.close()
|
|
e56c3be6dc3ab8bf31b7ce9a3d3db275b18207f0
|
Create sql-all.py
|
Django/sql-all.py
|
Django/sql-all.py
|
Python
| 0.000706 |
@@ -0,0 +1,203 @@
+$ ./manage.py sqlall name-app%0A%0A'''%0ACommandError: App 'name-app' has migrations. %0AOnly the sqlmigrate and sqlflush commands can be used when an app has migrations.%0A'''%0A%0ASo there before migrate to see it.%0A
|
|
43841114f4403b46e0ef077be6e0832ce690dfb2
|
add ipy_workdir
|
IPython/Extensions/ipy_workdir.py
|
IPython/Extensions/ipy_workdir.py
|
Python
| 0.000001 |
@@ -0,0 +1,640 @@
+#!/usr/bin/env python%0D%0A%0D%0Aimport IPython.ipapi%0D%0Aip = IPython.ipapi.get()%0D%0A%0D%0Aimport os%0D%0A%0D%0Aworkdir = None%0D%0Adef workdir_f(line):%0D%0A global workdir%0D%0A dummy,cmd = line.split(None,1)%0D%0A if os.path.isdir(cmd):%0D%0A workdir = cmd%0D%0A print %22Set workdir%22,workdir%0D%0A elif workdir is None:%0D%0A print %22Please set workdir first by doing e.g. 'workdir q:/'%22%0D%0A else:%0D%0A print %22Execute command in%22,workdir%0D%0A cwd = os.getcwd()%0D%0A os.chdir(workdir)%0D%0A try:%0D%0A ip.runlines(cmd)%0D%0A finally:%0D%0A os.chdir(cwd)%0D%0A%0D%0Aip.defalias(%22workdir%22,workdir_f)%0D%0A %0D%0A %0D%0A %0D%0A %0D%0A%0D%0A
|
|
b78ba3220a64e9b01b3fc8c61ada0e85dc1157fc
|
Implement data dumper
|
oeplatform/dumper.py
|
oeplatform/dumper.py
|
Python
| 0.000016 |
@@ -0,0 +1,1529 @@
+import oeplatform.securitysettings as sec%0Aimport sqlalchemy as sqla%0Afrom subprocess import call%0Aimport os%0A%0Aexcluded_schemas = %5B%0A%0A %22information_schema%22,%0A %22public%22,%0A %22topology%22,%0A %22reference%22,%0A%5D%0A%0A%0Adef connect():%0A engine = _get_engine()%0A return sqla.inspect(engine)%0A%0A%0Adef _get_engine():%0A engine = sqla.create_engine(%0A 'postgresql://%7B0%7D:%7B1%7D@%7B2%7D:%7B3%7D/%7B4%7D'.format(%0A sec.dbuser,%0A sec.dbpasswd,%0A sec.dbhost,%0A sec.dbport,%0A sec.dbname))%0A return engine%0A%0A%0Ainsp = connect()%0Afor schema in insp.get_schema_names():%0A if schema not in excluded_schemas:%0A if not os.path.exists(sec.datarepowc + schema):%0A os.mkdir(sec.datarepowc + schema)%0A for table in insp.get_table_names(schema=schema):%0A if not table.startswith('_'):%0A if not os.path.exists(sec.datarepowc + schema + '/' + table):%0A os.mkdir(sec.datarepowc + schema + '/' + table)%0A L = %5B'pg_dump', '-h', sec.dbhost, '-U', sec.dbuser, '-d',%0A sec.dbname, '-F', 'd', '-f',%0A sec.datarepowc + schema + '/' + table, '-t',%0A schema + '.' + table, '-w', %5D%0A print(L)%0A call(L)%0A call(%5B'tar', '-zcf',%0A sec.datarepowc + schema + '/' + table + '.tar.gz',%0A sec.datarepowc + schema + '/' + table%5D)%0A call(%5B'rm', '-r',%0A sec.datarepowc + schema + '/' + table%5D)%0A
|
|
0254fbea5218e332dc0c54af198aa2b29381878b
|
Composite two smiley on top of the famous Michael jordan crying face
|
python/composite.py
|
python/composite.py
|
Python
| 0.999822 |
@@ -0,0 +1,904 @@
+import requests%0Aimport json%0A%0A# Composite two smiley on top of the famous Michael jordan crying face.%0A# A more sophisticated approach would be to extract the face landmarks using facelandmarks and composite something on the different regions.%0A# https://pixlab.io/#/cmd?id=merge for more info.%0A%0Areq = requests.post('https://api.pixlab.io/merge',%0A%09headers=%7B'Content-Type':'application/json'%7D,%0A%09data=json.dumps(%7B%0A%09%09'src':'https://pbs.twimg.com/media/CcEfpp0W4AEQVPf.jpg',%0A%09%09'key':'My_Pix_Key',%0A%09%09'cord':%5B%0A%09%09%7B%0A%09%09 'img': 'http://www.wowpng.com/wp-content/uploads/2016/10/lol-troll-face-png-image-october-2016-370x297.png',%0A%09%09 'x': 30,%0A%09%09 'y': 320%0A%09%09%7D,%0A%09%09%7B%0A%09%09 'img': 'http://orig08.deviantart.net/67d1/f/2010/216/6/7/lol_face_by_bloodyhalfdemon.png',%0A%09%09 'x': 630,%0A%09%09 'y': 95%0A%09%09%7D%5D%0A%09%7D)%0A)%0Areply = req.json()%0Aif reply%5B'status'%5D != 200:%0A%09print (reply%5B'error'%5D)%0Aelse:%0A%09print (%22Pic Link: %22+ reply%5B'link'%5D)%0A
|
|
8ce580d1f0890f72ab60efa4219de26b64ece897
|
Add example skeleton script
|
example/example.py
|
example/example.py
|
Python
| 0.000001 |
@@ -0,0 +1,1446 @@
+#!/usr/bin/env python%0A%0Aimport sys%0Afrom argparse import ArgumentParser%0Afrom getpass import getpass%0A%0Aclass BigFixArgParser(ArgumentParser):%0A name = %22hodor.py %5Boptions%5D%22%0A%0A def __init__(self):%0A description = %22A tool for creating a smarter planet%22%0A usage = %22%22%22Options:%0A -h, --help Print this help message and exit%0A -s, --server SERVER%5B:PORT%5D REST API server and port%0A -u, --user USER%5B:PASSWORD%5D REST API user and password%0A -k, --insecure Don't verify the HTTPS connection to the server%0A -c, --cacert FILE CA certificate used to verify the server's HTTPS%0A certificate%22%22%22%0A%0A super(BigFixArgParser, self).__init__(add_help=False,%0A usage=usage, description=description)%0A%0A self.add_argument('-k', '--insecure', action='store_true')%0A self.add_argument('-c', '--cacert')%0A self.add_argument('-u', '--user', required=True)%0A self.add_argument('-s', '--server', required=True)%0A%0A def parse_args(self):%0A self.usage = %22%7B0%7D%5Cn%5Cn%7B1%7D%5Cn%5Cn%7B2%7D%22.format(self.name,%0A self.description, self.usage)%0A%0A if '-h' in sys.argv or '--help' in sys.argv:%0A print(self.usage)%0A sys.exit()%0A%0A args = super(BigFixArgParser, self).parse_args()%0A%0A if ':' not in args.user:%0A prompt = %22Enter password for user '%7B0%7D': %22.format(args.user)%0A args.user = args.user + ':' + getpass(prompt)%0A%0A return args%0A%0Aparser = BigFixArgParser()%0Aprint(parser.parse_args())%0A
|
|
30a4cb3794d52d1743dc482f2c2a83ced1dcbd90
|
Make a clean report along with BLEU scores
|
session2/report.py
|
session2/report.py
|
Python
| 0.000001 |
@@ -0,0 +1,1992 @@
+import argparse, codecs, logging%0Aimport unicodecsv as csv%0Afrom nltk.align.bleu_score import bleu%0Aimport numpy as np%0A%0Adef setup_args():%0A parser = argparse.ArgumentParser()%0A parser.add_argument('src', 'Source file')%0A parser.add_argument('target', 'Translated data')%0A parser.add_argument('gold', 'Gold output file')%0A parser.add_argument('model', 'Model Name')%0A args = parser.parse_args()%0A return args%0A%0Adef main():%0A logging.basicConfig(format='%25(asctime)s : %25(levelname)s : %25(message)s', level=logging.INFO)%0A args = setup_args()%0A logging.info(args)%0A%0A f = codecs.open('%25s-%25s.csv'%25 (args.out, args.suffix), 'w')%0A csv_f = csv.writer(f, delimiter=',', encoding='utf-8')%0A%0A src_lines = codecs.open(args.src, 'r', 'utf-8').readlines()%0A src_lines_nounk = codecs.open(args.src + '.nounk', 'r', 'utf-8').readlines()%0A%0A target_lines = codecs.open(args.target, 'r', 'utf-8').readlines()%0A target_lines_nounk = codecs.open(args.target + '.nounk', 'r', 'utf-8').readlines()%0A%0A gold_lines = codecs.open(args.gold, 'r', 'utf-8').readlines()%0A gold_lines_nounk = codecs.open(args.gold + '.nounk', 'r', 'utf-8').readlines()%0A%0A data = %5B'Src', 'Src_UNK', 'Target_UNK', 'Target', 'Gold_UNK', 'Gold', 'BLEU'%5D%0A%0A num_lines = len(gold_lines)%0A logging.info('Num Lines: %25d'%25 num_lines)%0A%0A%0A bleu_scores = %5B%5D%0A for index in range(num_lines):%0A data = %5B%5D%0A data.append(src_lines_nounk%5Bindex%5D.strip())%0A data.append(src_lines%5Bindex%5D.strip())%0A%0A data.append(target_lines%5Bindex%5D.strip())%0A data.append(target_lines_nounk%5Bindex%5D.strip())%0A%0A data.append(gold_lines%5Bindex%5D.strip())%0A data.append(gold_lines_nounk%5Bindex%5D.strip())%0A%0A bleu_score = bleu(target_lines%5Bindex%5D.split(), %5Bgold_lines%5Bindex%5D.split()%5D, %5B1%5D)%0A bleu_scores.append(bleu_score)%0A data.append(str(bleu_score))%0A csv_f.writerow(data)%0A%0A logging.info('Average BLEU Score: %25f'%25 np.mean(bleu_scores))%0A%0Aif __name__ == '__main__':%0A main()
|
|
31bb487a2f75268cb0b60ef4539935df83b68a84
|
Add auto solver for "W3-Radix Sorts".
|
quiz/3-radixsort.py
|
quiz/3-radixsort.py
|
Python
| 0 |
@@ -0,0 +1,1656 @@
+#!/usr/bin/env python3%0A%0A%0Adef make_arr(text):%0A return text.strip().split(' ')%0A%0A%0Adef print_arr(arr):%0A for t in arr:%0A print(t, end=' ')%0A print()%0A%0A%0Adef solve_q1(arr, time):%0A for t in range(len(arr%5B0%5D) - 1, time - 1, -1):%0A arr = sorted(arr, key=lambda x: x%5Bt%5D)%0A return arr%0A%0A%0Adef msd_radix_sort(arr, start, end, depth):%0A if end - start %3C= 1:%0A return%0A%0A global msd_radix_sort_left%0A if msd_radix_sort_left %3C= 0:%0A return%0A msd_radix_sort_left -= 1%0A%0A arr%5Bstart:end%5D = sorted(arr%5Bstart:end%5D, key=lambda x: x%5Bdepth%5D)%0A%0A pre_n = start%0A pre_v = arr%5Bpre_n%5D%5Bdepth%5D%0A for i in range(start, end):%0A if arr%5Bi%5D%5Bdepth%5D != pre_v:%0A pre_v = arr%5Bi%5D%5Bdepth%5D%0A msd_radix_sort(arr, pre_n, i, depth + 1)%0A pre_n = i%0A msd_radix_sort(arr, pre_n, end, depth + 1)%0A%0A%0Adef solve_q2(arr, time):%0A global msd_radix_sort_left%0A msd_radix_sort_left = time%0A msd_radix_sort(arr, 0, len(arr), 0)%0A return arr%0A%0A%0Adef solve_q3(arr):%0A k = arr%5B0%5D%5B0%5D%0A l = 0%0A m = l%0A h = len(arr) - 1%0A%0A while m %3C= h:%0A v = arr%5Bm%5D%5B0%5D%0A if v %3C k:%0A arr%5Bm%5D, arr%5Bl%5D = arr%5Bl%5D, arr%5Bm%5D%0A m += 1%0A l += 1%0A elif v == k:%0A m += 1%0A else: # arr%5Bm%5D %3E k%0A arr%5Bm%5D, arr%5Bh%5D = arr%5Bh%5D, arr%5Bm%5D%0A h -= 1%0A return arr%0A%0Aq1 = ' 4322 4441 1244 3122 1332 2131 4431 3113 2244 1241'%0Aq2 = ' 1324 3314 1122 3112 4423 3321 3344 4223 1412 1344 4314 4412 1333 2323 3243 '%0Aq3 = ' 5552 5255 3462 2614 6432 5252 6543 6152 5156 5434 '%0A%0Aprint_arr(solve_q1(make_arr(q1), 2))%0Aprint_arr(solve_q2(make_arr(q2), 3))%0Aprint_arr(solve_q3(make_arr(q3)))%0A
|
|
d959587c168424ed0d8e91a4a20ea36076a646b7
|
add forgotten __init__.py
|
dhcpcanon/__init__.py
|
dhcpcanon/__init__.py
|
Python
| 0.00035 |
@@ -0,0 +1,40 @@
+__version__ = %220.1%22%0A__author__ = %22juga%22%0A
|
|
98fe743217ebd7868d11d8518f25430539eae5a0
|
add regrresion example
|
example/simple_regression_example.py
|
example/simple_regression_example.py
|
Python
| 0 |
@@ -0,0 +1,967 @@
+from sklearn import datasets, metrics, preprocessing%0Afrom stacked_generalization.lib.stacking import StackedRegressor%0Afrom sklearn.ensemble import RandomForestRegressor%0Afrom sklearn.ensemble import GradientBoostingRegressor%0Afrom sklearn.ensemble import ExtraTreesRegressor%0Afrom sklearn.linear_model import LogisticRegression%0Afrom sklearn.linear_model import Ridge%0Afrom sklearn.linear_model import LinearRegression%0A%0A%0Aboston = datasets.load_boston()%0AX = preprocessing.StandardScaler().fit_transform(boston.data)%0Abreg = LinearRegression()%0Aregs = %5BRandomForestRegressor(n_estimators=50, random_state=1),%0A GradientBoostingRegressor(n_estimators=25, random_state=1),%0A ExtraTreesRegressor(),%0A Ridge(random_state=1)%5D%0Asr = StackedRegressor(breg,%0A regs,%0A n_folds=3,%0A verbose=0)%0Asr.fit(X, boston.target)%0Ascore = metrics.mean_squared_error(sr.predict(X), boston.target)%0Aprint (%22MSE: %25f%22 %25 score)
|
|
896270bcd99b26e4128fd35dd3821a59807ae850
|
Add the model.py file declarative generated from mysql.
|
doc/model/model_decla.py
|
doc/model/model_decla.py
|
Python
| 0 |
@@ -0,0 +1,1493 @@
+#autogenerated by sqlautocode%0A%0Afrom sqlalchemy import *%0Afrom sqlalchemy.ext.declarative import declarative_base%0Afrom sqlalchemy.orm import relation%0A%0Aengine = create_engine('mysql://monty:passwd@localhost/test_dia')%0ADeclarativeBase = declarative_base()%0Ametadata = DeclarativeBase.metadata%0Ametadata.bind = engine%0A%0Aclass Metering(DeclarativeBase):%0A __tablename__ = 'Metering'%0A%0A __table_args__ = %7B%7D%0A%0A #column definitions%0A date = Column(u'date', DATE())%0A id = Column(u'id', INTEGER(), primary_key=True, nullable=False)%0A sensor_id = Column(u'sensor_id', INTEGER(), ForeignKey('Sensor.id'))%0A value = Column(u'value', FLOAT())%0A%0A #relation definitions%0A Sensor = relation('Sensor', primaryjoin='Metering.sensor_id==Sensor.id')%0A%0A%0Aclass Sensor(DeclarativeBase):%0A __tablename__ = 'Sensor'%0A%0A __table_args__ = %7B%7D%0A%0A #column definitions%0A bus_adress = Column(u'bus_adress', VARCHAR(length=255))%0A description = Column(u'description', VARCHAR(length=255))%0A high_threshold = Column(u'high_threshold', FLOAT())%0A id = Column(u'id', INTEGER(), primary_key=True, nullable=False)%0A low_threshold = Column(u'low_threshold', FLOAT())%0A max_value = Column(u'max_value', FLOAT())%0A min_value = Column(u'min_value', FLOAT())%0A name = Column(u'name', VARCHAR(length=255))%0A unique_key = Column(u'unique_key', VARCHAR(length=255))%0A unit = Column(u'unit', VARCHAR(length=255))%0A unit_label = Column(u'unit_label', VARCHAR(length=255))%0A%0A #relation definitions%0A%0A%0A
|
|
7aab44f006a6412d8f169c3f9a801f41a6ea0a95
|
Remove start dates for the second time from draft dos2 briefs
|
migrations/versions/880_remove_invalid_draft_dos2_brief_dates_again.py
|
migrations/versions/880_remove_invalid_draft_dos2_brief_dates_again.py
|
Python
| 0.000002 |
@@ -0,0 +1,2077 @@
+%22%22%22Remove dates from draft dos2 briefs.%0AThis is identical to the previous migration but will be run again to cover any draft briefs with invalid%0Adates that could have appeared during the previous API rollout process (after the previous migration but before%0Athe code propogated fully to the ec2 instances).%0A%0ARevision ID: 880%0ARevises: 870%0ACreate Date: 2016-04-07%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '880'%0Adown_revision = '870'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Aframeworks_table = sa.Table(%0A 'frameworks',%0A sa.MetaData(),%0A sa.Column('id', sa.Integer, primary_key=True),%0A sa.Column('slug', sa.String, nullable=False, unique=True, index=True)%0A)%0A%0Abriefs_table = sa.Table(%0A 'briefs',%0A sa.MetaData(),%0A sa.Column('id', sa.Integer, primary_key=True),%0A sa.Column('framework_id', sa.Integer, nullable=False),%0A sa.Column('published_at', sa.DateTime, nullable=True),%0A sa.Column('data', sa.JSON, nullable=True)%0A)%0A%0A%0Adef upgrade():%0A %22%22%22Remove question and answer for startDate from briefs.data for draft dos2 briefs.%22%22%22%0A conn = op.get_bind()%0A%0A # SELECT id, data%0A # FROM briefs JOIN frameworks ON briefs.framework_id = frameworks.id%0A # WHERE frameworks.slug = 'digital-outcomes-and-specialists-2' AND briefs.published_at IS null;%0A query = briefs_table.join(%0A frameworks_table,%0A briefs_table.c.framework_id == frameworks_table.c.id%0A ).select(%0A sa.and_(%0A frameworks_table.c.slug == 'digital-outcomes-and-specialists-2',%0A briefs_table.c.published_at == sa.null()%0A )%0A ).with_only_columns(%0A (%0A briefs_table.c.id,%0A briefs_table.c.data%0A )%0A )%0A results = conn.execute(query).fetchall()%0A%0A for brief_id, brief_data in results:%0A if brief_data.pop('startDate', None) is not None:%0A # UPDATE briefs SET data = _brief_data WHERE id = _brief_id;%0A query = briefs_table.update().where(briefs_table.c.id==brief_id).values(data=brief_data)%0A conn.execute(query)%0A%0A%0Adef downgrade():%0A pass%0A
|
|
77ccb8db873c31ad2bd8318118410abab3141312
|
add __version__.py
|
europilot/__version__.py
|
europilot/__version__.py
|
Python
| 0.001013 |
@@ -0,0 +1,126 @@
+__title__ = 'europilot'%0A__description__ = 'End to end driving simulation inside Euro Truck Simulator 2'%0A__version__ = '0.0.1'%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.