repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
MaximeKjaer/dailyprogrammer-challenges | Challenge-172/02-Intermediate-2/password_maker.py | Python | mit | 774 | 0.009044 | #!/usr/bin/python
import sys
if len(sys.argv)<2:
print "\nYou need to provide an argument!\nThe syntax | is the following:\n\npython password_maker.py [password]"
exit()
import hashlib
import uuid
password = sys.argv[1]
sal | t = uuid.uuid4().hex
hashed_password = hashlib.sha512(password + salt).hexdigest()
f = open('salt.txt', 'wb')
f.write(salt)
f.close()
f = open('encrypted.txt', 'wb')
f.write(hashed_password)
f.close()
print "\n=============================================================================\n\n"
print "Your password has... |
shimpe/frescobaldi | setup.py | Python | gpl-2.0 | 3,867 | 0.00931 | import os
import sys
from frescobaldi_app import appinfo
try:
from setuptools import setup
USE_SETUPTOOLS = True
except ImportError:
from distutils.core import setup
USE_SETUPTOOLS = False
def packagelist(directory):
"""Returns a sorted list with package names for all packages under the given dir... | amming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Multimedia :: Sound/Audio',
'Topic :: Multimedia :: Graphics',
'Topic :: Text Editors',
]
setup(
name = appinfo.name,
ver... | ion = appinfo.long_description,
maintainer = appinfo.maintainer,
maintainer_email = appinfo.maintainer_email,
url = appinfo.url,
license = appinfo.license,
scripts = scripts,
packages = packages,
package_data = package_data,
data_files = data_files,
classifiers = classifiers,
... |
Maxence1/flask-wtf | examples/recaptcha/app.py | Python | bsd-3-clause | 1,299 | 0 | from flask import Flask, render_template, flash, session, redirect, url_for
from wtforms import Te | xtAreaField
from wtforms.validators import DataRequired
from flask.ext.wtf import Form
from flask.ext.wtf.r | ecaptcha import RecaptchaField
DEBUG = True
SECRET_KEY = 'secret'
# keys for localhost. Change as appropriate.
RECAPTCHA_PUBLIC_KEY = '6LeYIbsSAAAAACRPIllxA7wvXjIE411PfdB2gt2J'
RECAPTCHA_PRIVATE_KEY = '6LeYIbsSAAAAAJezaIq3Ft_hSTo0YtyeFG-JgRtu'
app = Flask(__name__)
app.config.from_object(__name__)
class CommentF... |
liam2/larray | larray/example.py | Python | gpl-3.0 | 3,569 | 0.001961 | import os
from pathlib import Path
import larray as la
_TEST_DIR = Path(__file__).parent / 'tests'
EXAMPLE_FILES_DIR = _TEST_DIR / 'data'
AVAILABLE_EXAMPLE_DATA = {
'demography': EXAMPLE_FILES_DIR / 'demography.h5',
'demography_eurostat': EXAMPLE_FILES_DIR / 'demography_eurostat.h5'
}
EXAMPLE_EXCEL_TEMPLATE... | ays used in the tutorial so that | all examples in it can be reproduced.
Parameters
----------
name : str
Example data to load. Available example datasets are:
- demography
- demography_eurostat
Returns
-------
Session
Session containing one or several arrays.
Examples
--------
>>> ... |
Ultimaker/Cura | plugins/UM3NetworkPrinting/src/Models/Http/ClusterPrintJobConstraints.py | Python | lgpl-3.0 | 717 | 0.004184 | # Copyright (c) 2021 Ultimake | r B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Optional
from ..BaseModel | import BaseModel
class ClusterPrintJobConstraints(BaseModel):
"""Class representing a cloud cluster print job constraint"""
def __init__(self, require_printer_name: Optional[str] = None, **kwargs) -> None:
"""Creates a new print job constraint.
:param require_printer_name: Unique name of th... |
RexFuzzle/sfepy | sfepy/base/plotutils.py | Python | bsd-3-clause | 4,703 | 0.03317 | import numpy as nm
try:
import matplotlib.pyplot as plt
import matplotlib as mpl
except (ImportError, RuntimeError):
plt = mpl = None
#print 'matplotlib import failed!'
from sfepy.base.base import output, pause
def spy(mtx, eps=None, color='b', **kwargs):
"""
Show sparsity structure of a `sci... | pe[0])
irs, ics = aux.nonzero()
for ii in iis:
ir, i | c = irs[ii], ics[ii]
print '%5d %5d %11.4e %11.4e %9.2e %9.2e'\
% (ir, ic, mtx1[ir,ic], mtx2[ir,ic], mtx_da[ir,ic], mtx_dr[ir,ic] )
print 'total: %d' % len( iis )
##
# 13.12.2005, c
# 14.12.2005
# 15.12.2005
# 18.07.2007
def plot_matrix_diff( mtx1, mtx2, delta, legend, mode ):
eps = 1e-... |
isovic/aligneval | src/plot_with_seabourne_v2.py | Python | mit | 37,633 | 0.048628 | #! /usr/bin/python
import os;
import sys;
try:
import numpy as np;
except Exception, e:
USE_MATPLOTLIB = False;
print e;
print 'Warning: NumPy not installed!';
exit(0);
USE_MATPLOTLIB = True;
try:
import matplotlib.pyplot as plt;
except Exception, e:
USE_MATPLOTLIB = False;
print e;
print 'Warning: Matplotl... | max != ''):
i = len(x_value) - 1;
while i >= 0:
if (float(x_value[i]) < float(x_max)):
x_max_index = i + 1;
break;
i -= 1;
i = 0;
while i < len(y_values):
mapper_name = GetMapperName(labels[i]);
# linestyle or ls [ '-' | '--' | '-.' | ' | :' | 'steps' | ...]
if (i < 5):
plt.plot(x_value[x_min_index:x_max_index], y_values[i][x_min_index:x_max_index], label=mapper_name);
elif (i < 10):
plt.plot(x_value[x_min_index:x_max_index], y_values[i][x_min_index:x_max_index], '--', label=mapper_name);
else:
plt.plot(x_value[x_min_index:x_max_ind... |
Achuth17/scikit-bio | skbio/io/tests/test_fastq.py | Python | bsd-3-clause | 30,554 | 0.000425 | # ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... | a_as_illumina.fastq',
| 'misc_dna_as_sanger.fastq',
'misc_dna_original_sanger.fastq',
'misc_rna_as_illumina.fastq',
'misc_rna_as_sanger.fastq',
'misc_rna_original_sanger.fastq',
'sanger_full_range_as_illumina.fastq',
'sanger_full_range_as_sanger.fastq',
's... |
bastianh/evelink | tests/cache/test_shelve.py | Python | mit | 815 | 0.006135 | import os
import tempfile
from tests.com | pat import unittest
from evelink.cache.shelf import ShelveCache
class ShelveCacheTestCase(unittest.TestCase):
def setUp(self):
self.cache_dir = tempfile.mkdtemp()
self.cache_path = os.path.join(self.cache_dir, 'shelf')
self.cache = ShelveCache(self.cache_path)
def tearDown(self):
... | try:
os.rmdir(self.cache_dir)
except OSError:
pass
def test_cache(self):
self.cache.put('foo', 'bar', 3600)
self.assertEqual(self.cache.get('foo'), 'bar')
def test_expire(self):
self.cache.put('baz', 'qux', -1)
self.assertEqual(self.cache.get('baz'),... |
mozilla/addons-server | src/olympia/shelves/migrations/0018_delete_shelfmanagement.py | Python | bsd-3-clause | 304 | 0 | # Generated by Django 3.2.4 on 2021-07-28 17:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shelves', '0017_auto_20210726_1422'),
]
operations = [
migrations.D | eleteModel(
name='ShelfManagement',
| ),
]
|
Cimbali/pympress | pympress/talk_time.py | Python | gpl-2.0 | 10,340 | 0.003967 | # -*- coding: utf-8 -*-
#
# talk_time.py
#
# Copyright 2017 Cimbali <me@cimba.li>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License,... | der (builder.Builder): The builder from which to load widgets.
ett (`int`): the estimated time for the talk, in seconds.
timing_tracker: (:class:`~pympress.extras.TimingReport`): to inform when the slides change
autoplay: (:class:`~pympress.dialog.AutoPlay`): to adjust the timer display if we’re | auto-playing/looping slides
"""
#: Elapsed time :class:`~Gtk.Label`
label_time = None
#: Clock :class:`~Gtk.Label`
label_clock = None
#: Time at which the counter was started, `int` in seconds as returned by :func:`~time.time()`
restart_time = 0
#: Time elapsed since the beginning of t... |
bwasti/caffe2 | caffe2/python/operator_test/rank_loss_operator_test.py | Python | apache-2.0 | 4,147 | 0.000241 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as n... | X[0] - X[1])))),
delta=1e-2 * abs(np.asscalar(dx[0])))
self.assertEqual(np.asscalar(dx[0]), np.asscalar(-dx[1]))
delta = 1e-3
up_x = np.array([[X[0] + delta], [X[1]]], dtype=np.float32)
down_x = np.array([[X[ | 0] - delta], [X[1]]], dtype=np.float32)
workspace.FeedBlob('up_x', up_x)
workspace.FeedBlob('down_x', down_x)
new_net = core.Net('new_net')
new_net.PairWiseLoss(['up_x', 'label'], ['up_output'])
new_net.PairWiseLoss(['down_x', 'label'], ['down_output'])
plan = core.Plan(... |
openSUSE/vdsm | vdsm/SecureXMLRPCServer.py | Python | gpl-2.0 | 7,492 | 0.00307 | # Copyright 2008 Red Hat, Inc. and/or its affiliates.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the fo... | t, timeout)
self.ca_certs = ca_certs
self.cert_reqs = cert_reqs
def connect(self):
"Connect to a host on a given (SSL) port."
sock = socket.create_connection((self.host, self.po | rt), self.timeout)
if self._tunnel_host:
self.sock = sock
self._tunnel()
# DK added: pass ca_cert to sslsocket
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
ca_certs=self.ca_certs, server_side=False,
... |
duplocloud/duploiotagent | AWSIoTPythonSDK/core/shadow/shadowManager.py | Python | apache-2.0 | 3,636 | 0.00385 | # /*
# * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
# * A copy of the License is located at
# *
# * http://aws.amazon.com/apache2.0
# *
# * or i... | "delta"]
def __init__(self, srcShadowName, srcActionName):
if srcActionName is None o | r srcActionName not in self._actionType:
raise TypeError("Unsupported shadow action.")
self._shadowName = srcShadowName
self._actionName = srcActionName
self.isDelta = srcActionName == "delta"
if self.isDelta:
self._topicDelta = "$aws/things/" + str(self._shadowNa... |
ACJTeam/enigma2 | lib/python/Components/Language.py | Python | gpl-2.0 | 5,188 | 0.024752 | # -*- coding: UTF-8 -*-
import gettext
import locale
import os
from Tools.Directories import SCOPE_LANGUAGE, resolveFilename
class Language:
def __init__(self):
gettext.install('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), unicode=0, codeset="utf-8")
gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANG... | t.textdomain("enigma2")
self.activeLanguage = 0
self.catalog = None
self.lang = {}
self.langlist = []
# FIXME make list dynamically
# name, iso-639 language, iso-3166 country. Please don't mix language&country!
self.addLanguage("Arabic", "ar", "AE", "ISO-8859-15")
self.addLanguage("Български", "bg", "BG... | ddLanguage("Dansk", "da", "DK", "ISO-8859-15")
self.addLanguage("Deutsch", "de", "DE", "ISO-8859-15")
self.addLanguage("Ελληνικά", "el", "GR", "ISO-8859-7")
self.addLanguage("English", "en", "EN", "ISO-8859-15")
self.addLanguage("Español", "es", "ES", "ISO-8859-15")
self.addLanguage("Eesti", "et", "EE", "ISO-... |
ZacharyJacobCollins/Fallen | tagger.py | Python | mit | 554 | 0.00361 | from sentence import Sentence
from | textblob import TextBlob
from itertools import chain
from collections import Counter
def findSubject(lines):
sentences = []
| if len(lines) == 0:
print "messages are empty"
return None
for m in lines:
sentences.append(Sentence(m).nouns)
if len(sentences) != 0:
maxNoun = Counter(list(chain(*sentences))).most_common()[0]
else:
print "No nouns"
return None
if maxNoun[1] >= 2:
... |
cl4u2/chirp | chirpui/mainapp.py | Python | gpl-3.0 | 67,000 | 0.001866 | # Copyright 2008 Dan Smith <dsmith@danplanet.com>
# Copyright 2012 Tom Hayward <tom@tomh.us>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... | set_action_sensitive(i, eset is not None)
def ev_status(self, editorset, msg):
self.sb_radio.pop(0)
self.sb_radio.push(0, msg)
| def ev_usermsg(self, editorset, msg):
self.sb_general.pop(0)
self.sb_general.push(0, msg)
def ev_editor_selected(self, editorset, editortype):
mappings = {
"memedit" : ["view", "edit"],
}
for _editortype, actions in mappings.items():
for _act... |
datastax/python-driver | tests/integration/standard/test_udts.py | Python | apache-2.0 | 31,537 | 0.002568 | # Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | insertion of unprepared, registered UDTs
"""
c = TestCluster()
s = c.connect(self.keyspace_name, wait_for_all_pools=True)
s.execute("CREATE TYPE user (age int, name text)")
s.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)")
Use | r = namedtuple('user', ('age', 'name'))
c.register_user_type(self.keyspace_name, "user", User)
s.execute("INSERT INTO mytable (a, b) VALUES (%s, %s)", (0, User(42, 'bob')))
result = s.execute("SELECT b FROM mytable WHERE a=0")
row = result[0]
self.assertEqual(42, row.b.age)
... |
moonso/vcf_parser | vcf_parser/utils/__init__.py | Python | mit | 481 | 0 | from __future__ import absolute_import
from .check_info import check_info_annotation
from .rank_scores import build_rank_score_dict
from .build_info import (build | _info_string, bu | ild_info_dict)
from .build_compounds import build_compounds_dict
from .build_models import build_models_dict
from .build_vep import (build_vep_string, build_vep_annotation)
from .split_genotype import split_genotype
from .format_variant import format_variant
from .split_variants import split_variants
|
mdcic/ssp | setup.py | Python | gpl-3.0 | 1,270 | 0.002362 | # -*- coding: utf-8 -*-
from setuptools import setup
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
DESCRIPTION = open(os.path.join(here, 'DESCRIPTION')).read()
version = '0.0.1'
setup(name='ssp',
version=version,
description="System Service Processor communication library",
long_... | 'ssp.chassis.ipmi'
],
scripts=['tools/ssp-chassis-scanner'],
include_package_data=True,
install_requires=[
'pywbem',
'paramiko'
] |
)
|
jhogan/boog | boog.py | Python | unlicense | 23,069 | 0.013308 | #! /bin/python
# jessehogandeliamariahogan
#vim: set ts=4 sw=4 et
import copy
import os
import curses
import time
import sys
false=False
true=True
class char:
def __init__(self, x, y, char):
self.x = x
self.y = y
self.letter = char
def str(self):
return "%s,%s %s" % (self.x, sel... | i in range(5):
self.chars[i] = [None] * 5
y=0
if false:
for line in str.split("\n"):
x=0
for c in line:
self.chars[y][x] = char(x, y, c)
x += 1
y += 1
def isvalid(self):
... | or x in range(5):
for y in range(5):
c = self.getchar(x,y)
if c == None or (c.letter.isupper() and c.letter != 'Q'):
return false
return true
def getchar(self, x, y):
return self.chars[y][x]
def setchar(self, x, y, c):
sel... |
ikn/wearhouse | game/engine/gfx/graphic.py | Python | gpl-3.0 | 51,464 | 0.002856 | """Basic graphic representing an image.
---NODOC---
TODO:
- use subsurface for crop transform (but requires rect to be within surface)
- GraphicView probably doesn't work if in different manager - need to have own _dirty?
- something that wraps a Graphic to be a copy of it, like Animation does, and has .graphic se... | self.resize(*rect.size)
@property
def x (self):
"""``x`` co-ordinate of the top-left corner of :attr:`rect`."""
return self._rect[0]
@x.setter
def x (self, x):
r = Rect(self._rect)
r[0] = x
self.rect = r
@property
def y (self):
"""``... | f._rect)
r[1] = y
self.rect = r
@property
def pos (self):
"""``(``:attr:`x` ``,`` :attr:`y` ``)``."""
return self._rect.topleft
@pos.setter
def pos (self, pos):
self.rect = (pos, self._rect.size)
@property
def w (self):
"""Width of :attr:`rect`;... |
sniemi/SamPy | sandbox/src1/TCSE3-3rd-examples/src/py/examples/simviz/simviz1cpGUI_unit.py | Python | bsd-2-clause | 1,881 | 0.006911 | #!/usr/bin/env python
"""
As simviz1cpGUI.py, but the parameters have dimensions.
Only the import statement for SimViz differs from simviz1cpGUI.py.
"""
import sys, os, math
from scitools.ParameterInterface import Parameters, AutoSimVizGUI
from simviz1cp_unit import SimViz
class SimVizGUI(SimViz):
def __init__(... | = AutoSimVizGUI()
if layout == 'sort':
# widgets sorted in columns:
self.GUI.make_prmGUI(self.master, self.p,
sort_widgets=1,
height=300, pane=1)
else:
# only one column of input parameters:
... | ulate: run oscillator code for solving the
differential equation for the spring system.
Visualize: run Gnuplot to make plots in PNG and PostScript
format and on the screen (optional). Plots are stored
in the subdirectory with name equal to 'case'.
"""
self.GUI.make_buttonGUI(self.master,
buttons=[(... |
Carryzhou/MyPython- | dir_walk1.py | Python | gpl-3.0 | 388 | 0.012887 | #!/ | usr/bin/python
#use recursion to read a dir
import os
def dir_walk(path):
li = os.listdir(path)
for p in li:
pathname = os.path.join(path, p)
if not os.path.isfile(pathname):
dir_walk(pathname)
else:
print pathname
def test(path):
dir_walk(path)
if __name_... | __":
path = "/home/zhoulihua/kk"
test(path)
|
unnikrishnankgs/va | venv/lib/python3.5/site-packages/html5lib/treewalkers/lxmletree.py | Python | bsd-2-clause | 5,980 | 0.000836 | from __future__ import absolute_import, division, unicode_literals
from six import text_type
from lxml import etree
from ..treebuilders.etree import tag_regexp
from . import _base
from .. import ihatexml
def ensure_str(s):
if s is None:
return None
elif isinstance(s, text_type):
return s
... | len__(self):
return len(self.obj)
class TreeWalker(_base.NonRecursiveTreeWalker):
def __init__(self, tree):
if hasattr(tree, "getroot"):
tree = Root(tree)
elif isinstance(tree, list):
tree = FragmentRoot(tree)
_base.NonRecursiveTreeWalker.__init__(self, tree... | tails(self, node):
if isinstance(node, tuple): # Text node
node, key = node
assert key in ("text", "tail"), "Text nodes are text or tail, found %s" % key
return _base.TEXT, ensure_str(getattr(node, key))
elif isinstance(node, Root):
return (_base.DOCUMEN... |
Stargrazer82301/CAAPR | CAAPR/CAAPR_AstroMagic/PTS/pts/core/tools/serialization.py | Python | mit | 1,823 | 0.004391 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | odules
import json
import pickle
# -----------------------------------------------------------------
def to_json(object):
"""
This function ...
:param self:
:return:
"""
return json.dumps(object, default=lambda o: o.__dict__, sort_keys=True, in | dent=4)
# -----------------------------------------------------------------
def dump(object, path, method="pickle", protocol=None):
"""
This function ...
:param object:
:param path:
:param method:
:param protocol:
:return:
"""
# Serialize using pickle
if method == "pickle":
... |
infinyte/oppia | core/controllers/reader.py | Python | apache-2.0 | 18,063 | 0.000111 | # Copyright 2014 The Oppia 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 ... | 'INTERACTION_SPECS': interaction_registry.Registry.get_all_specs(),
'SHARING_OPTIONS': | SHARING_OPTIONS.value,
'SHARING_OPTIONS_TWITTER_TEXT': SHARING_OPTIONS_TWITTER_TEXT.value,
'additional_angular_modules': additional_angular_modules,
'can_edit': (
bool(self.username) and
self.username not in config_domain.BANNED_USERNAMES.value and
... |
wesm/arrow | python/pyarrow/json.py | Python | apache-2.0 | 858 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF AN | Y
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from pyarrow._json import ReadOptions, ParseOptions, read_json # noqa
|
gluke77/rally | tests/unit/task/test_context.py | Python | apache-2.0 | 9,745 | 0 | # Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | x.setup = mock.MagicMock()
ctx.cleanup = mock.MagicMock()
with ctx as entered_ctx:
self.assertEqual(ctx, entered_ctx)
ctx.cleanup.assert_called_once_with()
def tes | t_lt(self):
@context.configure(name="lt", order=fakes.FakeContext.get_order() - 1)
class FakeLowerContext(fakes.FakeContext):
pass
ctx = mock.MagicMock()
self.assertTrue(FakeLowerContext(ctx) < fakes.FakeContext(ctx))
self.assertFalse(fakes.FakeContext(ctx) < FakeLo... |
rustychris/stompy | setup.py | Python | mit | 603 | 0.001658 | from distutils.core import setup
setup(
nam | e='stompy',
version='0.1',
packages=['stompy', 'stompy.grid', 'stompy.io', 'stompy.io.local',
'stompy.model', 'stompy.model.delft', 'stompy.model.fvcom',
'stompy.model.pypart', 'stompy.model.suntans',
| 'stompy.plot', 'stompy.plot.cmaps',
'stompy.spatial'],
package_data={'stompy':['tide_consts.txt']},
license='MIT',
url="https://github.com/rustychris/stompy",
author="Rusty Holleman",
author_email="rustychris@gmail.com",
long_description=open('README.md').read(),
)
|
diegojromerolopez/djshop | src/djshop/apps/club/migrations/0008_auto_20170523_1218.py | Python | mit | 752 | 0.00266 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-05-23 12:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('club', '0007_member_autocheckout_secret_code_checksum'),
]
operations = [
| migrations.AddField(
model_name='member',
name='email',
field=models.EmailField(blank=True, default='', max_length=254, verbose_name='Email of the member'),
),
migrations.AddField(
model_name='member',
name='telephone_number',
fi... | arField(blank=True, default='', max_length=32, verbose_name='Last name of the member'),
),
]
|
dotKom/onlineweb4 | apps/mailinglists/appconfig.py | Python | mit | 138 | 0 | from django.apps import AppConfi | g
class MailinglistsConfig(AppC | onfig):
name = 'apps.mailinglists'
verbose_name = 'Mailinglists'
|
Jufianto/LearnPython | fistLearn/konsidi.py | Python | mit | 165 | 0.042424 | a = raw_input("Yakin ? | (y/t) : ")
list = ["y","Y"]
| if a in list :
print "baiklah"
elif a in ["t","T"]:
print "Sayang Sekali"
else:
print "Liat Pilihan OON" |
ehiggs/hanythingondemand | hod/utils.py | Python | gpl-2.0 | 2,111 | 0.004263 | #!/usr/bin/env python
# ##
# Copyright 2009-2015 Ghent University
#
# This file is part of hanythingondemand
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),... | is not available."""
try:
__import__(modname)
return orig
except ImportError as err:
def error(*args):
raise ImportError("%s; required module '%s' is not available" % (err, modname))
return error
return wrap
def setup_diagnostic_envi | ronment():
"""
When we run diagnostic functions (e.g. genconfig, help-template), we need to
pretend we are in a job so we poke some values into the environment.
"""
if 'PBS_DEFAULT' not in os.environ:
os.environ['PBS_DEFAULT'] = 'pbs-master'
os.environ['PBS_JOBID'] = '123.%s' % os.enviro... |
anthonyfok/frescobaldi | frescobaldi_app/snippet/edit.py | Python | gpl-2.0 | 8,855 | 0.004178 | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
... | ugh it is
# constructed with a parent, that's why we save it in an unused attribute.
self._highlighter = highlight.Highlighter(self.text.document())
Matcher(self.text)
gadgets.indenter.Indenter(self.text)
self.text.installEventFilter(gadgets.homekey.handler)
self.text.i | nstallEventFilter(arrowkeys.handler)
wordboundary.handler.install_textedit(self.text)
completer.Completer(self.text)
if name:
self.titleEntry.setText(snippets.title(name, False) or '')
self.text.setPlainText(snippets.text(name))
ac = self.parent().par... |
ikreymer/pywb | pywb/utils/loaders.py | Python | gpl-3.0 | 14,279 | 0.00021 | from __future__ import absolute_import
"""
This module provides loaders for local file system and over http
local and remote access
"""
import os
import hmac
import requests
import yaml
import six
from six.moves.urllib.parse import unquote_plus, urlsplit, urlencode
import time
import pkgutil
import base64
import cg... | nfig = yaml.load(configdata, Loader=yaml.Loader)
finally:
no_except_close(configdata)
return config
# =============================================================================
def load_overlay_config(main_env_var, main_default_file='',
overlay_env_var='', overlay_file=''):... | os.path.expandvars(configfile)
config = load_yaml_config(configfile)
config = config or {}
overlay_configfile = os.environ.get(overlay_env_var, overlay_file)
if overlay_configfile:
overlay_configfile = os.path.expandvars(overlay_configfile)
config.update(load_yaml_config(overlay... |
camilortte/Recomendador | manage.py | Python | mit | 255 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Recomendad | or.settings")
from django.core.management import execute_f | rom_command_line
execute_from_command_line(sys.argv)
|
MrTheodor/espressopp | testsuite/interaction_potentials/unittest/PTestFENE.py | Python | gpl-3.0 | 1,424 | 0.007725 | # Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of t... | in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU | General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
import espressopp.unittest
from espressopp.interaction.FENE import *
from espressopp import Real3D, infinity
class Test0FENE(espressopp.unittest.TestCase) :
def test0Energy(self) :
fene=FENE(... |
pism/pism | util/plot_profiling.py | Python | gpl-3.0 | 4,816 | 0.001869 | #!/usr/bin/env python3
import pylab as plt
import numpy as np
from argparse import ArgumentParser
import importlib
import sys
import os.path
""" Produce pie charts using PISM's profiling output produced using
the -profile option. """
parser = ArgumentParser()
parser.add_argument("FILE", nargs=1)
options = parser.pars... | 51, 128, 114),
(128, 177, 211), (253, 180, | 98), (179, 222, 105), (252, 205, 229),
(217, 217, 217), (188, 128, 189), (204, 235, 197), (255, 237, 111)]
colors = np.array(colors) / 255.0
n_procs = r.size
s = r.Stages["time-stepping loop"]
big_events = ["basal_yield_stress",
"stress_balance",
"surface",
"ocean",... |
atvcaptain/enigma2 | lib/python/Plugins/Extensions/AtileHD/plugin.py | Python | gpl-2.0 | 28,142 | 0.028889 | # -*- coding: utf-8 -*-
#This plugin is free software, you are allowed to
#modify it (if you keep the license),
#but you are not allowed to distribute/publish
#it without source code (this version and your modifications).
#This means you also have to distribute
#source code of your modifications.
from __future__ impo... | lf["key_red"] = Label(_("Cancel"))
self["key_green"] = Label(_("OK"))
self["myActionMap"] = ActionMap(["SetupActions", "ColorActions"],
{
"ok": self.keyOk,
"green": self.keyOk,
"cancel": self.keyCancel,
"red": self.keyCancel,
}, -1)
self.createChoiceList()
def createChoiceList(self):
list = []... | tr(x[0])))
self["choicelist"].l.setList(list)
def keyOk(self):
returnValue = self["choicelist"].l.getCurrentSelection()[1]
if returnValue is not None:
self.close(returnValue)
else:
self.keyCancel()
def keyCancel(self):
self.close(None)
class AtileHD_Config(Screen, ConfigListScreen):
skin = """
... |
sjl767/woo | examples/shapepack.py | Python | gpl-2.0 | 1,342 | 0.046945 | import woo.core, woo.dem
from woo.dem import *
import woo.utils
from minieigen import *
from math import *
from woo import utils
m=woo.utils.defaultMaterial()
zeroSphere=woo.utils.sphere((0,0,0),.4) # sphere which is entirely inside the thing
for p in [woo.utils.sphere((0,0,0),1,mat=m),woo.utils.ellipsoid((0,0,0),semi... | sp=woo.dem.ShapePack()
sp.add([p.shape,zeroSphere.shape])
r=sp.raws[0]
if isinstance(r,SphereClumpGeom):
for i in range | (len(r.radii)): print r.centers[i],r.radii[i]
else:
for rr in r.rawShapes: print rr,rr.className,rr.center,rr.radius,rr.raw
# print [i for i in r.rawShapes]
r.recompute(div=10)
print 'equivRad',r.equivRad,p.shape.equivRadius
print 'volume',r.volume,p.mass/m.density
print 'inertia',r.ine... |
GiovanniConserva/TestDeploy | venv/Lib/site-packages/clyent/errors.py | Python | bsd-3-clause | 150 | 0.013333 | from __future__ | import absolute_import, print_function, unicode_literals
class ShowHelp(Exception):
pass
class ClyentError | (Exception):
pass
|
GoogleCloudPlatform/rad-lab | radlab-launcher/radlab.py | Python | apache-2.0 | 44,933 | 0.010816 | #!/usr/bin/env python3
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | .strip()
# Setting up required attributes for any RAD Lab module deployment
env_path,tfbucket,orgid,billing_acc,folderid,randomid = module_deploy_common_settin | gs(action,module_name,setup_path,varcontents,projid,tfbucket)
# Utilizing Terraform Wrapper for init / apply / destroy
env(action, orgid, billing_acc, folderid, env_path, randomid, tfbucket, projid)
print("\nGCS Bucket storing Terrafrom Configs: "+ tfbucket +"\n")
print("\nTERRAFORM DEPLOYMENT COM... |
rawjam/django-allauth | allauth/socialaccount/providers/twitter/provider.py | Python | mit | 2,869 | 0.005228 | from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth.provider import OAuthProvider
from allauth.socialaccount.models import SocialApp, SocialToken
import oauth2 as oauth
import urllib, urllib2, json
class TwitterAccount... |
if callback: callback(full_url, data)
return json.loads(data)
return None
def __unicode__(self):
screen_name = self.get_screen_name()
| return screen_name or super(TwitterAccount, self).__unicode__()
class TwitterProvider(OAuthProvider):
id = 'twitter'
name = 'Twitter'
package = 'allauth.socialaccount.providers.twitter'
account_class = TwitterAccount
providers.registry.register(TwitterProvider)
|
thingsboard/thingsboard-gateway | tests/converters/test_bytes_can_uplink_converter.py | Python | apache-2.0 | 7,578 | 0.00066 | # Copyright 2020. ThingsBoard
#
# Licensed under the Apache L | icense, Version 2.0 (the "License"];
# you may not use this file except in compliance with the License.
# You may obtain a copy of t | he 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 fo... |
bonyuta0204/NetDissec | src/adeseg.py | Python | mit | 5,296 | 0.000189 | import colorname
import glob
import os
import re
import numpy
from loadseg import AbstractSegmentation
from scipy.io import loadmat
from scipy.misc import imread
from collections import namedtuple
class AdeSegmentation(AbstractSegmentation):
def __init__(self, directory=None, version=None):
# Default to v... | pe[-2:] if arrs else (1, 1)
return result, shape
# End of contract for AbstractSegmentation
def seg_filename(self, n):
'''Returns the segmentation filename for the nth dataset image.'''
return re.sub(r'\.jpg$', '_seg.png', self.filename(n) | )
def part_filenames(self, n):
'''Returns all the subpart images for the nth dataset image.'''
filename = self.filename(n)
level = 1
result = []
while True:
probe = re.sub(r'\.jpg$', '_parts_%d.png' % level, filename)
if not os.path.isfile(probe):
... |
washimimizuku/tools-for-biology | toolsforbiology/urls.py | Python | mit | 306 | 0.013072 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
| # Examples:
# url(r'^$', 'toolsforbiology.views.home', name='home'),
# url | (r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/v2018_03_01/operations/_policy_assignments_operations.py | Python | mit | 47,343 | 0.004964 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | yAssignments/{policyAssignmentName}')
path_format_arguments = {
"scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True),
"policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
... | query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
... |
dask/zict | zict/common.py | Python | bsd-3-clause | 1,419 | 0.001409 | try:
from collections.abc import Mapping, MutableMapping
except ImportError:
from collections import Mapping, MutableMapping
class ZictBase(MutableMapping):
"""
Base class for zict mappings.
"""
def update(*args, **kwds):
# Boilerplate for implementing an update() method
if no... | gs[0]
if isinstance(other, Mapping) or hasattr(other, "items"):
items += other.items()
else:
# Assuming (key, value) pairs
items += other
if kwds:
items += kwds.items()
self._do_update(items)
def _do_update(self, it... | ms:
self[k] = v
def close(self):
"""
Release any system resources held by this object.
"""
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(z):
"""
Close *z* if possible.
"""
if hasattr(z, "close"):
... |
pudo/jsonmapping | jsonmapping/transforms.py | Python | mit | 2,402 | 0 | import re
import six
from hashlib import sha1
from unidecode import unidecode
import normality
COLLAPSE = re.compile(r'\s+')
def transliterate(text):
""" Utility to properly transliterate text. """
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text
def coalesce(mapping... | unctions like upper(), lower() and strip(). """
def func(mapping, bind, values):
for v in values:
if isinstance(v, six.string_types):
v = getattr(v, name)()
yield v
return func
def hash(mapping, bind, values):
""" Generate a sha1 for each of the given values... | yield sha1(v.encode('utf-8')).hexdigest()
def clean(mapping, bind, values):
""" Perform several types of string cleaning for titles etc.. """
categories = {'C': ' '}
for value in values:
if isinstance(value, six.string_types):
value = normality.normalize(value, lowercase=False, collap... |
vivekanand1101/neutron | neutron/tests/api/test_allowed_address_pair.py | Python | apache-2.0 | 5,586 | 0 | # Copyright 2014 OpenStack Foundation
# 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://w | ww.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 i | mplied. See the
# License for the specific language governing permissions and limitations
# under the License.
import netaddr
from neutron.tests.api import base
from neutron.tests.tempest import config
from neutron.tests.tempest import test
CONF = config.CONF
class AllowedAddressPairTestJSON(base.BaseNetwork... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/moto/ec2/models.py | Python | agpl-3.0 | 37,412 | 0.001123 | import copy
import itertools
from collections import defaultdict
from boto.ec2.instance import Instance as BotoInstance, Reservation
from moto.core import BaseBackend
from .exceptions import (
InvalidIdError,
DependencyViolationError,
InvalidDHCPOptionsIdError
)
from .utils import (
random_ami_id,
... | n reservation.instances:
if instance.id == instance_id:
return instance
def get_reservations_by_instance_ids(self, instance_ids):
""" Go through all of the reservations and filter to onl | y return those
associated with the given instance_ids.
"""
reservations = []
for reservation in self.all_reservations(make_copy=True):
reservation_instance_ids = [instance.id for instance in reservation.instances]
matching_reservation = any(instance_id in reservat... |
xpharry/Udacity-DLFoudation | tutorials/reinforcement/gym/gym/scoreboard/client/util.py | Python | mit | 1,383 | 0.003615 | import functools
import logging
import os
import random
import sys
import time
from gym import error
logger = logging.getLogger(__name__)
def utf8(value):
if isinstance(value, unicode) and sys.version_info < (3, 0):
return value.encode('utf-8')
else:
return value
def file_size(f):
return... | _size
def retry_exponential_backoff(f, errors, max_retries=5, interval=1):
@functools.wraps(f)
def wrapped(*args, **kwargs):
num_retries = 0
caught_errors = []
while True:
try:
result = f(*args, **kwargs)
except errors as e:
logger... | caught_errors.append(e)
if num_retries < max_retries:
backoff = random.randint(1, 2 ** num_retries) * interval
logger.error("Retrying in %.1fs..." % backoff)
time.sleep(backoff)
num_retries += 1
else:
... |
twitter/pants | tests/python/pants_test/base/test_deprecated.py | Python | apache-2.0 | 7,818 | 0.012024 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import warnings
from builtins import object, str
from contextlib import contextmanager
i... | @deprecated(self.FUTURE_VERSION, subject=subject)
d | ef deprecated_function():
return expected_return
with self._test_deprecation() as extract_deprecation_warning:
self.assertEqual(expected_return, deprecated_function())
self.assertIn(subject, str(extract_deprecation_warning()))
def test_removal_version_required(self):
with self.assertRaises... |
eaobservatory/hedwig | test/test_file_poll.py | Python | gpl-3.0 | 6,323 | 0 | # Copyright (C) 2016-2018 East Asian Observatory
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version... | def test_poll_process_moc(self):
facility_id = self.db.ensure_facility('test')
# Should initially find nothing to process.
self.assertEqual(process_moc(self.db), 0)
# Insert a new MOC.
moc = MOC(order=10, cells=(1234, 4321))
moc_id = self.db.add_moc(
faci... | s = self.db.search_moc(facility_id, None, moc_id=moc_id)
self.assertEqual(list(mocs.keys()), [moc_id])
self.assertEqual(mocs[moc_id].state, AttachmentState.NEW)
# Should now find 1 MOC to process.
self.assertEqual(process_moc(self.db), 1)
# The MOC should now be marked READY.
... |
castlecms/castle.cms | castle/cms/browser/survey.py | Python | gpl-2.0 | 849 | 0.002356 | from zope.interface import Interface
from zope import schema
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from z3c.form import form
class ICastleSurvey(Interface):
survey_api_url = schema.TextLine(
title=u'GovSurvey API URL',
description=u'GovSurvey.us API URL; https://g... | d=False
)
class CastleSurvey(form.Form):
label = u"Survey"
description = u"A GovSurvey survey"
formErrorsMessage = 'There were errors in a Castle Survey'
ignoreContext = True
schema = ICastleSurvey
template = ViewPageTe | mplateFile("templates/survey.pt")
|
girder/girder_worker | tests/integration/common_tasks/common_tasks/test_tasks/fib.py | Python | apache-2.0 | 440 | 0 | from girder | _worker.utils import girder_job
from girder_worker.app import app
@girder_job(title='Fibonacci Job')
@app.task
def fibonacci(n, **kwargs):
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
@app.task(bind=True)
def f | ib_seq(self, n, **kwargs):
if n < 0:
raise Exception('Must pass in positive integer!')
for _n in range(1, n+1):
print('%s: %s' % (_n, fibonacci(_n)))
|
xorpaul/shinken | shinken/dispatcher.py | Python | agpl-3.0 | 29,613 | 0.004424 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you c... | tr(self.conf, sat_ty | pe))
# for each satellite, we look if current arbiter have a specific satellitemap value setted for this satellite
# if so, we give this map to the satellite (used to build satellite URI later)
if arbiter is None:
continue
key = sat_type[:-1] + '_name' ... |
lduarte1991/edx-platform | openedx/core/djangoapps/schedules/migrations/0001_initial.py | Python | agpl-3.0 | 1,410 | 0.004965 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
| ('student', '0010_auto_20170207_0458'),
]
operations = [
migrations.CreateModel(
name='Schedule',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('created', model_utils.fields.Auto... | LastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)),
('active', models.BooleanField(default=True, help_text='Indicates if this schedule is actively used')),
('start', models.DateTimeField(help_text='Date this schedule went into effect')),
... |
owlabs/incubator-airflow | airflow/settings.py | Python | apache-2.0 | 13,677 | 0.001975 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | ous connections
# the pool will allow is pool_size + max_overflow,
# and the total number of “sleeping” connections the pool will allow is pool_size.
# max_overflow can be set to -1 to indicate no overflow limit;
# no limit will be placed on the total number
# of concurrent conne... | etint('core', 'SQL_ALCHEMY_MAX_OVERFLOW', fallback=10)
# The DB server already has a value for wait_timeout (number of seconds |
zaqwes8811/ml-cv | ml_tests.py | Python | apache-2.0 | 241 | 0.020747 | from sklearn import preprocessing
import numpy as np
X = np.array([[ 1., -1., 2.],
[ 2., 0., | 0.],
[ 2., 0., | 0.],
[ 0., 1., -1.]])
print X
X_scaled = preprocessing.scale(X)
print X_scaled
|
jbs1/jhack14 | rooms.py | Python | gpl-2.0 | 1,739 | 0.016676 | from classes import *
sign = Object('sign', 'To the left is a sign.', 'The sign says: Den of Evil')
opening = Room('opening', 'You are standing in front of a cave.', {}, {'sign' : sign})
#sign.set_room(opening)
opening_w = Room('opening_w', 'You are standing in front of an impassable jungle. There is nothing here yo... | ng_w.add_room('east', opening)
opening.add_room('west', opening_w)
opening_e = Room('opening_e', 'You are standing in front of an impassable jungle. There is nothing here you can do.')
opening_e.add_room('west', opening)
opening.add_room('east', opening_e)
lamp = Item('Lamp', 'On the ground is an old and rusty oil l... | ed = Room('shed', 'In the dim light from outside you can see a small and dirty room.', {'lamp':lamp}, {}, {}, 'The broken door blocks the entrance')
door=Object('door','The door barely hangs in its place', None, 'The door explodes under your force.', None, shed)
opening_s = Room('opening_s', 'There is a small shed at ... |
khchine5/django-shop | shop/urls/rest_api.py | Python | bsd-3-clause | 688 | 0.001453 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url, include
from rest_framework import routers
from shop.views.cart import CartViewSet, WatchViewSet
from | shop.views.checkout import CheckoutViewSet
from shop.views.catalog import ProductSelectView
router = routers.DefaultRouter() # TODO: try with trailing_slash=False
router.register(r'cart', CartViewSe | t, base_name='cart')
router.register(r'watch', WatchViewSet, base_name='watch')
router.register(r'checkout', CheckoutViewSet, base_name='checkout')
urlpatterns = [
url(r'^select_product/?$', ProductSelectView.as_view(), name='select-product'),
url(r'^', include(router.urls)),
]
|
CollabNet/puppet-bucky | bucky/collectd.py | Python | apache-2.0 | 13,071 | 0.00023 | # -*- coding: utf-8 -
#
# 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
... | :
self.converters = dict(DEFAULT_CONVERTERS)
| self._load_converters(cfg)
def convert(self, sample):
default = self.converters["_default"]
handler = self.converters.get(sample["plugin"], default)
try:
name = '.'.join(handler(sample) |
jcassee/django-analytical | tests/unit/test_tag_woopra.py | Python | mit | 3,458 | 0.000289 | """
Tests for the Woopra template tags and filters.
"""
import pytest
from django.contrib.auth.models import AnonymousUser, User
from django.http import HttpRequest
from django.template import Context
from django.test.utils import override_settings
from utils import TagTestCase
from analytical.templatetags.woopra imp... | ',
last_name='Lastname',
email="test@example.com"),
}))
assert 'var woo_visitor = '
'{"email": "test@example.com", "name": "Firstname Lastname"};' in r
@override_settings(ANALYTICAL_AUTO_IDENTIFY=True)
def test_identify_username_no_email... | ({'user': User(username='test')}))
assert 'var woo_visitor = {"name": "test"};' in r
@override_settings(ANALYTICAL_AUTO_IDENTIFY=True)
def test_no_identify_when_explicit_name(self):
r = WoopraNode().render(Context({
'woopra_name': 'explicit',
'user': User(username='impli... |
StackPointCloud/libcloud | libcloud/compute/drivers/gridspot.py | Python | apache-2.0 | 4,135 | 0.000242 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | ody and body['exception_name']:
raise GridspotAPIException(body['exception_name'])
return body
def parse_error(self):
# Gridspot 404s on invalid api key or instance_id
raise InvalidCredsError("Invalid api key/instance_id")
class GridspotConnection(ConnectionKey):
"""
... | ['api_key'] = self.key
return params
class GridspotNodeDriver(NodeDriver):
"""
Gridspot (http://www.gridspot.com/) node driver.
"""
type = Provider.GRIDSPOT
name = 'Gridspot'
website = 'http://www.gridspot.com/'
connectionCls = GridspotConnection
NODE_STATE_MAP = {
'Ru... |
benhoff/vexbot | vexbot/extensions/system.py | Python | gpl-3.0 | 1,216 | 0.001645 | import psutil
_mb_conversion = 1024 * 1024
def cpu_times(*args, **kwargs):
return psutil.cpu_times()
def cpu_count(logical=True, *args, **kwargs):
cores = psutil.cpu_count(logical)
if cores == 1:
word = 'Core'
else:
word = 'Cores'
return '{} CPU {}'.format(cores, word)
def cpu... | l_memory_total(*args, **kwargs):
total = int(psutil.virtual_memory().tot | al / _mb_conversion)
return '{} Mb'.format(total)
def virtual_memory_used(*args, **kwargs):
used = int(psutil.virtual_memory().used / _mb_conversion)
return '{} Mb'.format(used)
def swap(*args, **kwargs):
swap = psutil.swap_memory()
used = swap.used
total = swap.total
used = int(used/_mb... |
takeshik/metatweet-old | resource/configuration/global.py | Python | gpl-3.0 | 522 | 0.015326 | import clr
clr.AddRefer | ence("System")
clr.AddReference("System.Core")
clr.AddReference("Linx")
clr.AddReference("MetaTweetObjectModel")
clr.AddReference("MetaTweetFoundation")
from System import *
from System.Collections.Generic import *
from XSpect import *
from XSpect.MetaTweet import *
from XSpect.MetaTweet.Modul | es import *
from XSpect.MetaTweet.Requesting import *
def Create(body):
child = Dynamic.ExpandoObject()
for e in body:
IDictionary[String, Object].Add(child, e, body[e])
return child
|
astrilchuk/sd2xmltv | libschedulesdirect/common/program.py | Python | mit | 6,469 | 0.001082 | import logging
from datetime import date
from util import parse_date
from programtitles import ProgramTitles
from programeventdetails import ProgramEventDetails
from programdescriptionlist import ProgramDescriptionList
from programmetadata import ProgramMetadata
from programcast import ProgramCast
from programcrew impo... | ils = None # type: ProgramEventDetails
self.descriptions = None # type: ProgramDescriptionList
self.original_air_date = None # type: date
self.genres = [] # type: List[unicode]
self.episode_title = None # type: unicode
| self.metadata = None # type: ProgramMetadata
self.cast = [] # type: List[ProgramCast]
self.crew = [] # type: List[ProgramCrew]
self.show_type = None # type: unicode
self.has_image_artwork = False # type: bool
self.content_ratings = [] # type: List[ProgramConten... |
amaozhao/algorithms | algorithms/dp/fib.py | Python | mit | 1,513 | 0.003966 | def fib_recursive(n):
"""[summary]
Computes the n-th fibonacci number recursive.
Problem: This implementation is very slow.
approximate O(2^n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a p... | 1915075
def fib_iter(n):
"""[summary]
Works iterative approximate O(n)
A | rguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be positive integer'
fib_1 = 0
fib_2 = 1
sum = 0
if n <= 1:
return n
for i in range(n-1):
sum = fib_1 + fib_2
fib_1 = fib_2
... |
johnwlockwood/txt2vote | txttovote/info_extractors/tests/test_info_extractors.py | Python | apache-2.0 | 5,895 | 0.00017 | from operator import itemgetter
import unittest
from karld.conversion_operators import join_stripped_values
from karld.conversion_operators import join_stripped_gotten_value
from info_extractors import get_full_name
from info_extractors import get_phone
from info_extra | ctors import get_zip
from info_ | extractors import number_getter
from info_extractors import lower_getter
from info_extractors import lower_list_getter
from info_extractors import title_getter
from info_extractors import title_list_getter
from info_extractors import get_number_prefix
class TestValueJoiner(unittest.TestCase):
def test_join_stripp... |
gghezzo/prettypython | PythonEveryDay2015/MontyHall/tkintermh.py | Python | mit | 1,654 | 0.036276 | # Monty Hall and the gaot - GUI
# Adding a Tkinter Gui (pass 2 )
# Typer: Ginny C Ghezzo
# What I learned:
import random
from tkinter import *
import webbrowser
def playVideo():
url = "http://9gag.com/gag/6681409"
webbrowser.open(url, 1)
# todo: Wow this is crazy ugly
# steal this http://www.python-cou... | utton(root, text ="Ready?", command = playVideo).grid(row=2, columnspan =2)
doors = ["A", "B", "C"]
totWins = 0
again = 'y'
root = Tk().wm_title("Monty Hall ")
iuGrid(root)
while again == 'y':
initial = input("Door A, B or C : ").upper() # fix bad selection
action = input("Switch or Hold (S,H):").upper()
place... | in used] #omg ... hilarious
opened = random.choice(avail)
if action == "S":
avail = [door for door in doors if door not in [chosen, opened]]
chosen = avail[0]
youWin = (chosen == placed)
if youWin : print("Congratulations! You win! It was in ", placed)
else: print("Sorry it was in ", placed)
again = input... |
treverhines/RBF | rbf/pde/nodes.py | Python | mit | 22,858 | 0.000044 | '''
This module provides functions for generating nodes used for solving PDEs with
the RBF and RBF-FD method.
'''
from __future__ import division
import logging
import numpy as np
from scipy.sparse import csc_matrix
from scipy.sparse.csgraph import reverse_cuthill_mckee
from rbf.utils import assert_shape, KDTree
from... | nodes[:, None, :] - all_nodes[i, :])/d[:, :, None]**3
| # sum up all the forces for each node
direction = np.sum(forces, axis=1)
# normalize the net forces to one
direction /= np.linalg.norm(direction, axis=1)[:, None]
# in the case of a zero vector replace nans with zeros
direction = np.nan_to_num(direction)
# move in the direction of the force ... |
WPI-ARC/lightning_ros | scripts/RR_action_server.py | Python | bsd-3-clause | 22,385 | 0.004423 | #!/usr/bin/env python
"""
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, University of California, Berkeley
# All rights reserved.
# Authors: Cameron Lee (cameronlee@berkeley.edu) and Dmitry Berenson (
berenson@eecs.berkeley.edu)
#
# Redistribution and use in source and binary forms, with or without... | with an allowed
planning time.
Args:
start (list of float): A joint configuration corresponding to the
start position of the path.
goal (list of float): The jount configuration corresponding to the
goal position for the path.
Returns... | list of joint configurations corresponding to the planned
path.
"""
ret = None
planner_number = self.plan_trajectory_wrapper.acquire_planner()
if not self._need_to_stop():
ret = self.plan_trajectory_wrapper.plan_trajectory(start, goal, planner_number, self.curre... |
atumanov/ray | python/ray/rllib/evaluation/postprocessing.py | Python | apache-2.0 | 2,480 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import scipy.signal
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.annotations import DeveloperAPI
def discount(x, gamma):
return scipy.signal.lfilter([1], [... | traj[Postprocessing.VALUE_TARGETS] = (
traj[Postprocessing.ADVANTAGES] +
traj[SampleBatch.VF_PREDS]).copy().astype(np.float32)
else:
rewards_plus_v = np.concatenate(
[rollout[SampleBatch.REWARDS],
np.array([last_r])])
traj[Postprocessing.ADVANT... | out GAE
traj[Postprocessing.VALUE_TARGETS] = np.zeros_like(
traj[Postprocessing.ADVANTAGES])
traj[Postprocessing.ADVANTAGES] = traj[
Postprocessing.ADVANTAGES].copy().astype(np.float32)
assert all(val.shape[0] == trajsize for val in traj.values()), \
"Rollout stacked incorr... |
XeCycle/indico | indico/MaKaC/webinterface/pages/abstracts.py | Python | gpl-3.0 | 69,950 | 0.008806 | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... |
elif isinstance(status, review.AbstractStatusWithdrawn):
return _("Withdrawn")
elif isinstance(status, review.AbstractStatusDuplicated):
return _("Duplicated")
elif isinstance(status, review.AbstractStatusMerged):
| return _("Merged")
elif isinstance(status, (review.AbstractStatusProposedToAccept, review.AbstractStatusProposedToReject)):
return _("Under Review")
elif isinstance(status, (review.AbstractInConflict)):
return _("In Conflict")
return _("Submitted")
def getVars(sel... |
mariano/snakefire | snakefire/dialogs.py | Python | mit | 26,264 | 0.003884 | from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtWebKit
from renderers import MessageRenderer
from qtx import ClickableQLabel, IdleTimer, RowPushButton, SpellTextEditor
class AboutDialog(QtGui.QDialog):
def __init__(self, mainFrame):
super(AboutDialog, self).__init__(mainFrame)
... | x.addLayout(tableBox)
vbox.addWidget(optionsGroupBox)
vbox.addWidget(methodsGroupBox)
vbox.addLayout(hbox)
self.setLayout(vbox)
# Load settings
alertsSettings = self._mainFrame.getSettings("alerts")
matches = self._mainFrame.getSettings("matches")
self... | ttings["notify_ping"])
self._notifyOnInactiveTabField.setChecked(alertsSettings["notify_inactive_tab"])
self._notifyBlinkField.setChecked(alertsSettings["notify_blink"])
self._notifyNotifyField.setChecked(alertsSettings["notify_notify"])
if matches:
for match in matches:
... |
gem/oq-hazardlib | openquake/hmtk/sources/source_conversion_utils.py | Python | agpl-3.0 | 5,833 | 0.001372 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit is free software: you can redistribute
# it and/or modify it under the terms of the GNU Affero Gene... | pmf import PMF
from openquake.hazardlib.geo.nodalplane | import NodalPlane
from openquake.hazardlib import mfd
from openquake.hazardlib.scalerel import get_available_scalerel
from openquake.hazardlib.scalerel.base import BaseMSR
from openquake.hazardlib.scalerel.wc1994 import WC1994
SCALE_RELS = get_available_scalerel()
def render_aspect_ratio(aspect_ratio, use_default=Fa... |
OpenNumismat/open-numismat | OpenNumismat/ListView.py | Python | gpl-3.0 | 51,632 | 0.000775 | import operator
import pickle
import os.path
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, pyqtSignal, QSortFilterProxyModel
from PyQt5.QtCore import QCollator, QLocale
from PyQt5.QtCore import QAbstractProxyModel, QModelIndex, QItemSelectionModel
from PyQt5.QtCore import QRectF, QRect
from PyQt5.QtSql import ... | f.clearSorting()
else:
return False
| self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setDragDropOverwriteMode(False)
self.setDropIndicatorShown(True)
return True
def selectMode(... |
mbdriscoll/asp-old | tests/asp_module_tests.py | Python | bsd-3-clause | 18,180 | 0.00495 | import unittest2 as unittest
import asp.jit.asp_module as asp_module
import asp.codegen.cpp_ast as cpp_ast
from mock import Mock
class TimerTest(unittest.TestCase):
def test_timer(self):
pass
# mod = asp_module.ASPModule()
# mod.add_function("void test(){;;;;}", "test")
# # mod.test... | db.connection = Mock()
db.table_exists = Mock(return_value = True)
db.delete("foo", "foo_v1", "KEY")
db.connection.execute.assert_called_with("delete from test where fname=? and variant=? and key=?",
("foo", "foo_v1", "KEY"))
class ... | test_add_variant(self):
mock_backend = asp_module.ASPBackend(Mock(), None, Mock())
a = asp_module.SpecializedFunction("foo", mock_backend, Mock())
a.add_variant("foo_1", "void foo_1(){return;}")
self.assertEqual(a.variant_names[0], "foo_1")
self.assertEqual(len(a.variant_... |
janusnic/21v-python | unit_03/16.py | Python | mit | 1,009 | 0.011893 | L = ['SPAM!', 'eat', 'more', 'please']
del L[0] # delete one item
print L
del L[1:] # delete an entire section
print L # same as L[1:] = []
li = ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
print li.remove("z") ... |
print li
inventory = ["sword", "armor", "shield", "healing potion"]
print "In a great battle, your shield is destroyed."
del inventory[2]
print "Your inventory is now:"
print inventory
inventory = ["sword", "armor", "shield", "healing potion"]
del inventory[:2]
print inventory
scores = ["1"... | sn't in the high scores list."
# list high-score table
for score in scores:
print score |
ClearCorp/odoo-costa-rica | l10n_cr_hr_holidays/models/__init__.py | Python | agpl-3.0 | 140 | 0 | # -*- coding: utf-8 -*- |
# © 2016 ClearCorp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
i | mport l10n_cr_hr_holidays
|
brownhead/different-logger | dlogger/_ansify.py | Python | unlicense | 2,079 | 0 | ANSI_ESCAPE_CODES = {
"reset": 0,
"bold": 1,
"faint": 2,
"italic": 3,
"underline": 4,
"blink-slow": 5,
"blink-fast": 6,
"inverse": 7,
"conceal": 8,
"strike-through": 9,
"font-default": 10,
"font-1": 11,
"font-2": 12,
"font-3": 13,
"font-4": 14,
"font-5": 1... | "normal-intensity": 22,
"no-italic": 23,
"no-underline": 24,
"no-blink": 25,
"no-inverse": 27,
"no-conceal": 28,
"no-strike-through": 29,
"black": 30,
"red": 31,
"green": 32,
"yellow": 33,
"blue": 34,
"magenta": 35,
"cyan": 36,
"white": 3 | 7,
"color-default": 39,
"background-black": 40,
"background-red": 41,
"background-green": 42,
"background-yellow": 43,
"background-blue": 44,
"background-magenta": 45,
"background-cyan": 46,
"background-white": 47,
"background-default": 49,
"frame": 51,
"encircle": 52,
... |
root-mirror/root | bindings/pyroot/pythonizations/test/import_load_libs.py | Python | lgpl-2.1 | 3,705 | 0.004318 | import unittest
import re
import os
class ImportLoadLibs(unittest.TestCase):
"""
Test which libraries are loaded during importing ROOT
"""
# The whitelist is a list of regex expressions that mark wanted libraries
# Note that the regex has to result in an exact match with the library name.
kno... | hitelisted libraries after importing ROOT with the shown regex match:')
for l, r in zip(good_libs, matched_re):
print(' - {} ({})'.format(l, r))
import sys
sys.stdout.flush()
if bad_libs:
raise Exception('Found not whitelisted libraries after impo... | ' \
+ '\n - ' + '\n - '.join(bad_libs) \
+ '\nIf the test fails with a library that is loaded on purpose, please add it to the whitelist.')
if __name__ == '__main__':
unittest.main()
|
googleads/googleads-adxbuyer-examples | python/samples/v2_x/create_bidder_level_filter_set.py | Python | apache-2.0 | 7,717 | 0.005702 | #!/usr/bin/python
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | AULT_START_DATE = (_TODAY - timedelta(days=7)).strftime(
_D | ATE_FORMAT)
def main(ad_exchange_buyer, owner_name, body, is_transient):
try:
# Construct and execute the request.
filter_set = ad_exchange_buyer.bidders().filterSets().create(
ownerName=owner_name, isTransient=is_transient, body=body).execute()
print(f'FilterSet created for bidder: "{owner_name... |
PuffinWare/pistat | com/puffinware/pistat/db.py | Python | gpl-3.0 | 767 | 0.019557 | """
Copyright 2016 Puffin Software. All rights reserved.
"""
from com.puffinware.pistat.models import User, Location, Category, Thermostat, Sensor, Reading
from com.puffinware.pist | at import DB
from logging import getLogger
log = getLogger(__name__)
def setup_db(app):
DB.create_tables([User, Location, Category, Thermostat, Sensor, Reading], safe=True)
# This hook ensures that a connection is opened to handle any queries
# generated by the request.
@app.before_request
def _db_connect(... | s that the connection is closed when we've finished
# processing the request.
@app.teardown_request
def _db_close(exc):
if not DB.is_closed():
log.debug('DB Close')
DB.close() |
SINGROUP/pycp2k | pycp2k/classes/_screening3.py | Python | lgpl-3.0 | 306 | 0.003268 | from | pycp2k.inputsection import InputSection
class _screening3(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Rc_taper = None
self.Rc_range = None
self._name = "SCREENING"
self._keywords = {'Rc_range': 'RC_RANGE', 'Rc_ta | per': 'RC_TAPER'}
|
tboyce1/home-assistant | homeassistant/components/tado/entity.py | Python | apache-2.0 | 1,664 | 0 | """Base class for Tado entity."""
from homeassistant.helpers.entity import Entity
from .const import DEFAULT_NAME, DOMAIN, TADO_ZONE
class TadoDeviceEntity(Entity):
"""Base implementation for Tado device."""
def __init__(self, device_info):
"""Initialize a Tado device."""
super().__init__()
... | eEntity(Entity):
"""Base implementation for Tado zone."""
def __init__(self, zone_name, home_id, zone_id):
"""Initialize a | Tado zone."""
super().__init__()
self._device_zone_id = f"{home_id}_{zone_id}"
self.zone_name = zone_name
@property
def device_info(self):
"""Return the device_info of the device."""
return {
"identifiers": {(DOMAIN, self._device_zone_id)},
"name"... |
mongodb-labs/disasm | app/disasm_demangler.py | Python | apache-2.0 | 654 | 0.001529 | # Copyright 2016 MongoDB Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance | with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or impli... | the License for the specific language governing permissions and
# limitations under the License.
try:
from demangler import demangle
except:
from cppfilt import demangle
|
joopert/home-assistant | tests/components/nsw_rural_fire_service_feed/test_geo_location.py | Python | apache-2.0 | 8,960 | 0.00067 | """The tests for the NSW Rural Fire Service Feeds platform."""
import datetime
from unittest.mock import ANY
from aio_geojson_nsw_rfs_incidents import NswRuralFireServiceIncidentsFeed
from asynctest.mock import patch, MagicMock, call
from homeassistant.components import geo_location
from homeassistant.components.geo_... | 2018, 9, 22, 8, 0, tzinfo=datetime.timezone.utc
| ),
council_area="Council Area 1",
status="Status 1",
entry_type="Type 1",
size="Size 1",
responsible_agency="Agency 1",
)
mock_entry_2 = _generate_mock_feed_entry(
"2345", "Title 2", 20.5, (-31.1, 150.1), fire=False
)
mock_entry_3 = _generate_mock_feed_... |
Cisco-Talos/pyrebox | mw_monitor2/ida_scripts/mw_monitor_binary_log_reader.py | Python | gpl-2.0 | 1,419 | 0.001409 | # -------------------------------------------------------------------------
#
# Copyright (C) 2018 Cisco Talos Security Intelligence and Research Group
#
# PyREBox: Python scriptable Reverse Engineering Sandbox
# Author: Xabier Ugarte-Pedrero
#
# This program is free software; you can redistribute it and/or mod... | tributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURP | OSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# ------------------------------... |
citrix-openstack-build/neutron-fwaas | neutron_fwaas/openstack/common/eventlet_backdoor.py | Python | apache-2.0 | 4,924 | 0 | # Copyright (c) 2012 OpenStack Foundation.
# Administrator of the National Aeronautics and Space Administration.
# 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 a... | h to using pprint
# since it won't interact poorly with gettext, and it's easier to
# read the output too.
def displayhook(val):
if val is not None:
pprint.pprint(val)
sys.displayhook = displayh | ook
sock = _listen('localhost', start_port, end_port, eventlet.listen)
# In the case of backdoor port being zero, a port number is assigned by
# listen(). In any case, pull the port number out here.
port = sock.getsockname()[1]
LOG.info(
_LI('Eventlet backdoor listening on %(port)s for pr... |
miaerbus/timebank | user/models.py | Python | agpl-3.0 | 4,968 | 0.017519 | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Eduardo Robles Elvira <edulix AT gmail DOT com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at yo... | | Q(credits_payee=self)).filter(status__in=['r', 'd | '])
def karma(self):
'''
Average of the user's transfer scores
'''
karma = self.transfers_received.aggregate(Avg('rating_score'))
if karma['rating_score__avg']:
return int(karma['rating_score__avg'])
else:
return 0
|
xbmc/atv2 | xbmc/lib/libPython/Python/Lib/test/test_dummy_thread.py | Python | gpl-2.0 | 7,139 | 0.005043 | """Generic thread tests.
Meant to be used by dummy_thread and thread. To allow for different modules
to be used, test_main() can be called with the module to use as the thread
implementation as its sole argument.
"""
import dummy_thread as _thread
import time
import Queue
import random
import unittest
from test impo... | s called in main threat that
# KeyboardInterrupt is raise | d instantly.
self.failUnlessRaises(KeyboardInterrupt, _thread.interrupt_main)
class ThreadTests(unittest.TestCase):
"""Test thread creation."""
def test_arg_passing(self):
#Make sure that parameter passing works.
def arg_tester(queue, arg1=False, arg2=False):
"""Use to test... |
YangLiu928/NDP_Projects | Python_Projects/Python_MySQL/compare_FTD_code/scripts/merchandise_trade_exports.py | Python | mit | 1,458 | 0.009602 | import process_data
# process_data.process_concord(data_folder, output_folder)
# process_data.process_country(data_folder, output_folder)
# process_data.process_district(data_folder, output_folder)
# process_data.process_enduse(data_folder, output_folder)
# process_data.process_exp_comm(data_folder, output_folder)
# p... | t/{0}/'.format(folder)
file = open(output_folder + 'HSDESC.js')
results.append(file.read())
# the following means, the export and import are same in the | same year
print results[0]==results[1] and results[2]==results[3]
file2009 = open('../output/{0}/'.format(results[0]))
file2015 = open('../output/{0}/'.format(results[2]))
line1 = ''
line2 = ''
while (line1==line2):
line1 = file2009.readline()
line2 = file2015.readline()
print line1
print line2
print 'work com... |
mxamin/youtube-dl | youtube_dl/extractor/playwire.py | Python | unlicense | 2,407 | 0.001662 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
dict_get,
float_or_none,
)
class PlaywireIE(InfoExtractor):
_VALID_URL = r'https?://(?:config|cdn)\.playwire\.com(?:/v2)?/(?P<publisher_id>\d+)/(?:videos/v2|embed|config)/(?P<id>\d+)'
_TESTS = [... |
'params': {
| # m3u8 download
'skip_download': True,
},
}, {
# Multiple resolutions while bitrates missing
'url': 'http://cdn.playwire.com/11625/embed/85228.html',
'only_matching': True,
}, {
'url': 'http://config.playwire.com/12421/videos/v2/3389892/zeus.json',
... |
SecondLiners/GO2 | tests/sort_test.py | Python | gpl-3.0 | 3,787 | 0.003433 | import unittest
import webapp2
import main
import band
import gig
import datetime
from google.appengine.ext import testbed
class GigSortTestCase(unittest.TestCase):
TEST_BAND = 'Wild Rumpus'
# Needed to get webapp2 to use a WSGIApplication application instance,
# which is easier to configure in setUp().... | r = None
| self.request_stub.app = main.APPLICATION
webapp2.WSGIApplication.app = main.APPLICATION
webapp2.get_app().set_globals(main.APPLICATION, self.request_stub)
def tearDown(self):
self.testbed.deactivate()
def assertNotEmpty(self, obj):
self.assertTrue(obj is not None and len... |
rosarior/rua | rua/apps/icons/registry.py | Python | gpl-3.0 | 617 | 0.004862 | from __future__ import absolute_import
from django.utils.translation import ugettext_lazy as _
from smart_settings import LocalScope
from .icons im | port icon_icons_app
from .literals import DEFAULT_ICON_SET
name = 'icons'
label = _(u'Icons')
description = _(u'Handles the registration and rend | ering of icons and sprites.')
dependencies = ['app_registry']
icon = icon_icons_app
settings = [
{
'name': 'ICON_SET',
'default': DEFAULT_ICON_SET,
'description': _(u'Icon set to use to render all the icon in the project.'),
'scopes': [LocalScope()] # TODO: Cluster, Org, User
}
]... |
xranby/apitrace | glproc.py | Python | mit | 12,065 | 0.000663 | ##########################################################################
#
# Copyright 2010 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without res... | gl.org/registry/ABI/
public_symbols = set([
# GL 1.2 and ARB_multitexture
"glAccum",
"glAlphaFunc",
"glAreTexturesResident",
"glArrayElement",
"glBegin",
"glBindTexture",
"glBitmap",
"glBlendFunc",
"glCallList",
"glCallLists",
"glClear",
"glClearAccum",
"glClearCo... | "glClearIndex",
"glClearStencil",
"glClipPlane",
"glColor3b",
"glColor3bv",
"glColor3d",
"glColor3dv",
"glColor3f",
"glColor3fv",
"glColor3i",
"glColor3iv",
"glColor3s",
"glColor3sv",
"glColor3ub",
"glColor3ubv",
"glColor3ui",
"glColor3uiv",
"glColor... |
gjtempleton/matasano_cryptopals | set1/challenge_4.py | Python | mit | 59 | 0 | def detect_ | single_character_xor(ciphertext):
| return ""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.